Search code examples
pythonevaluatelambdifyevalf

Error evaluating a derivative on Python (with .subs, .evalf and .lambdify)


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.


Solution

  • 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