View Single Post
  #3   Spotlight this post!  
Unread 10-03-2006, 11:45
Bongle's Avatar
Bongle Bongle is offline
Registered User
FRC #2702 (REBotics)
Team Role: Mentor
 
Join Date: Feb 2004
Rookie Year: 2002
Location: Waterloo
Posts: 1,069
Bongle has a reputation beyond reputeBongle has a reputation beyond reputeBongle has a reputation beyond reputeBongle has a reputation beyond reputeBongle has a reputation beyond reputeBongle has a reputation beyond reputeBongle has a reputation beyond reputeBongle has a reputation beyond reputeBongle has a reputation beyond reputeBongle has a reputation beyond reputeBongle has a reputation beyond repute
Send a message via MSN to Bongle
Re: Visual Basic. Using a loop to solve the cosine function.

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
Code:
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.
Attached Thumbnails
Click image for larger version

Name:	approx.PNG
Views:	94
Size:	10.6 KB
ID:	4102  

Last edited by Bongle : 10-03-2006 at 11:48.