I want to graph taylor series in python use matplot

import matplotlib.pyplot as plt
import sympy as sy
import numpy as np


plt.title("Comparison of EXP(x), PP1, PP2")
plt.xlim(0-0.1, 3+0.2)
plt.ylim(0, 20+1)
plt.ylabel("y: values")

x=np.linspace(0.0, 3.0, 100)
plt.plot(x, np.exp(x), label="exp(x)")
plt.plot(x, np.exp(x).series(x, 0, 4), label="PP1")

I use Jupyter Notebook. I want to graph taylor series of exp(x). I just success to graph exp(x) but failed taylor seires of exp(x). Sympy library has taylor series fuction so I tried it but I don't understand what's the problem. below is the error message and graph.

Error Message

1 answer

  • answered 2018-10-17 07:57 William Lee

    sy.exp(x).series(x) creates a sympy expression, not a function

    you might want to convert it to a function

    from sympy.utilities.lambdify import lambdify
    x = sy.Symbol('x')
    exp_expr = sy.exp(x).series(x).removeO()
    exp_func = lambdify(x, exp_expr)

    and plot it out

    x_points = np.linspace(0.0, 3.0, 100)
    plt.plot(x_points, [exp_func(i) for i in x_points])