Log in

View Full Version : Visual Basic. Using a loop to solve the cosine function.


sanddrag
06-03-2006, 20:40
I need to do this http://upload.wikimedia.org/math/5/b/9/5b961cc29e6b786e7f231369cad0c4a3.png in Visual Basic.

Attached is what I have done so far. I can't get it to work right though. I am not a programmer and I'm really struggling with this. I think the problem is coming from instead of (2*n)factorial my program is doing (n factorial)*2. I don't know how to fix it.

It should be noted that the "n" in that equation corresponds to "Counter" in my program and "n" in my program represents the number of terms of the series (since we can't have it going ifinitely).

Hopefully someone can help. Thanks.

BotLobsta
06-03-2006, 21:56
One thing that I noticed is that in the factorial loop, you dont want to start at n-1, you want to start at FactNum - 1. What you are doing now in that nested for loop is (n-1)!*FactNum. This will only give you the correct value when Counter = n/2.

Bongle
10-03-2006, 11:45
That's a taylor series. Depending on how accurate you need it, one or two terms should be enough. For example, if you can make it accurate enough to 90 degrees, you can then use other tricks to determine the cosines.

For instance: 1-(x^2)/2 + (x^4)/24 - (x^6)/720 is accurate to about PI radians (90 degrees). You can check by graphing it next to a cosine function. Since the cosine function after PI radians is simply a mirror image of the cosine function before PI radians, you can use that to avoid having to determine the actual value beyond PI. After 2*PI is just repeats, so you can use that to determine cosines for values beyond 2*PI. Cosine is mirrored about the y-axis, so you know cos(-x) = cos(x), which means negatives aren't a problem.

So now, you can make a full cosine function

Function cos(radians As Double)
Dim answer As Double
'MsgBox ("cos input: " & radians)

If radians >= 0 And radians < 3.14159 Then
answer = 1 - (radians * radians) / 2 + (radians * radians * radians * radians) / 24 - (radians * radians * radians * radians * radians * radians) / 720 + (radians * radians * radians * radians * radians * radians * radians * radians) / 40320
ElseIf radians >= 3.14159 And radians < 2 * 3.14159 Then
answer = cos((2 * 3.14159) - radians)
ElseIf radians >= 2 * 3.14159 Then
answer = cos(radians - 2 * 3.14159)
ElseIf radians < 0 Then
answer = cos(0-radians)
End If

cos = answer

End Function

This is a pretty slow way of doing cosine, but it gets the job done. Also, the recursive calls can be eliminated, but then it would get somewhat ugly. Attached is a graph from excel showing the difference between what the above function outputs and what the actual cosine function outputs. It's quite close.