The Taylor series for the sin function is straightforward to implement. Note that any reference which gives a Taylor series for a trigonometric function will assume the input is in radians, unless specified otherwise.
PI = 3.141592653589793238462643383
def sin_taylor_series(x, terms=9):
# map x into the range -PI/2 to PI/2 for greatest accuracy
x %= 2*PI
if x > PI:
x -= 2*PI
if x < -PI/2:
x = -PI - x
elif x > PI/2:
x = PI - x
total = 0
denominator = 1
for i in range(1, 2*terms+2, 2):
denominator *= i
total += (x ** i) / denominator
denominator *= -(i + 1)
return total
At 9 terms, the max absolute error (compared with math.sin
) is under 10 ** -15
, which is about as good as you’re going to get by adding a lot of floating point numbers together.
Note that this is not a particularly efficient way of approximating the sin function.
2
solved How do I calculate sine/cosine/tangent from CORDIC, Taylor Series, or alternative in Python?