Hi all,
If you have ever wondered how the sin function works then this function should explain nicely.
It uses some standard reduction formulas and a Taylor series approximation of the sin function of 4 terms.(if you had highschool math this should make sense)
The difference between this function and Math.sin is usually smaller than 0.0000001
The sin Function is where the reduction formulas are contained and the sin_ex is where the taylor series approximation is. You can add more terms to make it more accurate but the difference will be extremely small.
vb.net Code:
Const pi As Double = 3.1415926535897931
Function Sin(ByVal x As Double) As Double 'valid for x > 0
x = x Mod (2 * pi)
If x < (pi / 2) And x > -(pi / 2) Then
Return Sin_ex(x)
Else
Return Sin_ex(pi - x)
End If
End Function
Function Sin_ex(ByVal x As Double) As Double 'Valid for [-pi/2;pi/2]
Return x - ((x ^ 3) / 6) + ((x ^ 5) / 120) - ((x ^ 7) / 5040) '+ ((x ^ 9) / 326880)
End Function
Some notes:
- Only for positive values
- It's in radians
- For some reason the approximation gets inaccurate for values between multiples of pi/2 and pi.(about accurate to the second decimal)
- this was compared to the Math.Sin Function. I assumed in was 100% correct
EDIT: If you want Cos, there is a Taylor series approximation for that as well, but you can implement cos using sin quite easily since cos(x) = sin(x+pi/2) . And if you have cos then tan is quite easy aswell since tan(x) = sin(x)/cos(x)