In [3]:
%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
from math import sin, cos, factorial


def f_sin(x, p):
    if p == 0:
        return sin(x)

        return x
    if p % 4 == 1:
        return cos(x)

    if p % 4 == 2:
        return -sin(x)

    if p % 4 == 3:
        return -cos(x)

    return sin(x)
In [4]:
def taylor(df, x, a, n):

    f = 0.0

    for i in range(n+1):
        term = df(a, i) * (x - a)**i / factorial(i)
        f += term

    return f
In [23]:
from IPython.html.widgets import interact, interactive, fixed
from  IPython.html.widgets import FloatSliderWidget as fWidget
from  IPython.html.widgets import IntSliderWidget as iWidget

x = 0.1
a = 0.8
n = 1

def plot_data(a, n):
    xs = np.linspace(-2, 2, 50)
    ts = [taylor(f_sin, i, a, n) for i in xs]

    plt.plot(xs, np.sin(xs))
    plt.plot(xs, ts)
    plt.xlim(-2,2)
    plt.ylim(-2,2)
    plt.axvline(a)
    plt.show()
    
interact(plot_data, 
         a = fWidget(value=0.8, min=-1.9, max=1.9),
         n = iWidget(value=2, min=1, max=8))