0

I am trying to separately compute the elements of a Taylor expansion and did not obtain the results I was supposed to. The function to approximate is x**321, and the first three elements of that Taylor expansion around x=1 should be: 1 + 321(x-1) + 51360(x-1)**2 For some reason, the code associated with the second term is not working. See my code below.

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

x = sy.Symbol('x')
f = x**321
x0 = 1
func0 = f.diff(x,0).subs(x,x0)*((x-x0)**0/factorial(0))
print(func0)
func1 = f.diff(x,1).subs(x,x0)*((x-x0)**1/factorial(1))
print(func1)
func2 = f.diff(x,2).subs(x,x0)*((x-x0)**2/factorial(2))
print(func2)

The prints I obtain running this code are

1
321x - 321
51360*(x - 1)**2

I also used .evalf and .lambdify but the results were the same. I can't understand where the error is coming from.

f = x**321
x = sy.Symbol('x')

def fprime(x):
    return sy.diff(f,x)

DerivativeOfF = sy.lambdify((x),fprime(x),"numpy")
print(DerivativeOfF(1)*((x-x0)**1/factorial(1)))
321*x - 321

I'm obviously just starting with the language, so thank you for your help.

  • What package is behind your sy ? Could your include your imports in the beginning of your code? – Sharku Sep 14 '18 at 11:46
  • Where is the error? From your output everything seems to work. You already printed the correct output – Sheldore Sep 14 '18 at 11:48
  • no I think she means in the second row there should be 321*(x-1) – Sharku Sep 14 '18 at 11:49
  • But that's just a printing issue with the output, not an error. Both forms are equivalent – Sheldore Sep 14 '18 at 11:50
  • Tell her that not me. Oh wait you just did :P – Sharku Sep 14 '18 at 11:52
  • I appologise,@Sharku the imports are import sympy as sy import numpy as np import math import matplotlib.pyplot as plt @Bazingaa I don't see how it could be a print error, if you could just explain please. – Elena T. Aguilar Sep 14 '18 at 12:38
  • What I was saying is that `321x - 321` or `321(x - 1)` are the same thing. But your headline says 'Error evaluating...'. So I just said that you can't call it an error. It's just a matter of SciPy output representation I guess. – Sheldore Sep 14 '18 at 12:42

1 Answers1

0

I found a beginners guide how to Taylor expand in python. Check it out perhaps all your questions are answered there:

http://firsttimeprogrammer.blogspot.com/2015/03/taylor-series-with-python-and-sympy.html

I tested your code and it works fine. like Bazingaa pointed out in the comments it is just an issue how python saves functions internally. One could argument that for a computer it takes less RAM to save 321*x - 321 instead of 321*(x - 1)**1. In your first output line it also gives you 1 instead of (x - 1)**0

Sharku
  • 1,052
  • 1
  • 11
  • 24