Skip to content Skip to sidebar Skip to footer

How Do I Calculate Sine/cosine/tangent From Cordic, Taylor Series, Or Alternative In Python?

I am making a library for math functions, intended to test and challenge my programming and math skills. A necessary part of this is trig: Sine, Cosine, Tangent, and derivatives/in

Solution 1:

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.141592653589793238462643383defsin_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 = 1for i inrange(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.

Post a Comment for "How Do I Calculate Sine/cosine/tangent From Cordic, Taylor Series, Or Alternative In Python?"