pythontrigonometrytaylor-series

Approximating sin using the Taylor series


I'm trying to calculate sin(x) using Taylor series without using factorials.

import math, time
import matplotlib.pyplot as plot

def sin3(x, i=30):
    x %= 2 * math.pi
    n = 0
    dn = x**2 / 2
    for c in range(4, 2 * i + 4, 2):
        n += dn
        dn *= -x**2 / ((c + 1) * (c + 2))
    return x - n

def draw_graph(start = -800, end = 800):
    y = [sin3(i/100) for i in range(start, end)]
    x = [i/100 for i in range(start, end)]

    y2 = [math.sin(i/100) for i in range(start, end)]
    x2 = [i/100 for i in range(start, end)]

    plot.fill_between(x, y, facecolor="none", edgecolor="red", lw=0.7)
    plot.fill_between(x2, y2, facecolor="none", edgecolor="blue", lw=0.7)
    plot.show()

When you run the draw_graph function it uses matplotlib to draw a graph, the redline is the output from my sin3 function, and the blue line is the correct output from the math.sin method.

enter image description here

As you can see the curve is not quite right, it's not high or low enough (seems to peak at 0.5), and also has strange behavior where it generates a small peak around 0.25 then drops down again. How can I adjust my function to match the correct output of math.sin?


Solution

  • You have the wrong equation for sin(x), and you also have a messed up loop invariant.

    The formula for sin(x) is x/1! - x^3/3! + x^5/5! - x^7/7!..., so I really don't know why you're initializing dn to something involving x^2.

    You also want to ask yourself: What is my loop invariant? What is the value of dn when I reach the start of my loop. It is clear from the way you update dn that you expect it to be something involving x^i / i!. Yet on the very first iteration of the loop, i=4, yet dn involves x^2.

    Here is what you meant to write:

    def sin3(x, i=30):
        x %= 2 * math.pi
        n = 0
        dn = x
        for c in range(1, 2 * i + 4, 2):
            n += dn
            dn *= -x**2 / ((c + 1) * (c + 2))
        return n