%reset -f
from sympy import * # import everything from sympy module
init_printing() # for nice math output
## forcing plots inside browser
%matplotlib inline
x = symbols('x')
Find 4-th degree Taylor polynomial of at . Plot and Taylor polynomial on the same window
## Finding Taylor polynomial
a = pi/2
f = sin(x)
T = f.subs(x,a) \
+ diff(f,x,1).subs(x,a)*(x-a) \
+ diff(f,x,2).subs(x,a)*(x-a)**2/2 \
+ diff(f,x,3).subs(x,a)*(x-a)**3/factorial(3) \
+ diff(f,x,4).subs(x,a)*(x-a)**4/factorial(4)
T
## plotting f(x) and T(x) in same window
p = plot(f,T, (x,a - 4, a + 4),show=False, legend=True)
p[0].line_color = 'blue'
p[1].line_color = 'green'
p[0].label = 'f(x)'
p[1].label = 'T(x)'
p.show()
Find 20-th degree Taylor polynomial of at . Plot and Taylor polynomial on the same window
## evaluation of T
a = 1
n = 20
f = log(x)
T = f.subs(x,a)
for k in range(1,n+1):
df = diff(f,x,k)
T = T + df.subs(x,a)*(x-a)**k/factorial(k)
T
## plotting f(x) and T(x) in same window
p = plot(f,T, (x, 0.5, 2),show=False, legend=True)
p[0].line_color = 'blue'
p[1].line_color = 'green'
p[0].label = 'f(x)'
p[1].label = 'T(x)'
p.show()