So I have to write a python script for finding the root of a function using Newton's Method, and my code isn't computing a float when evaluating the derivative at a point, it's only evaluating the sin(x) part, leaving e^x and log(2) as they are. I'm stuck, please help. This is my code so far:

from sympy import *

x=symbols('x')

f="(e**x)+(2**(-x))+2*cos(x) - 6"
func=sympify(f)
fdiff=Derivative(func, x) #this returns an expression for the derivative
val=fdiff.doit().subs({x: 0.4})
print(val) #this should output 0.187681....  instead it returns another expression

PS: evalf doesn't work either, neither does subs(x, 0.4)

1

There are 1 best solutions below

3
On

Using E instead of e:

In [19]: x=symbols('x')
    ...: 
    ...: f="(E**x)+(2**(-x))+2*cos(x) - 6"
    ...: func=sympify(f)
In [20]: func
Out[20]: 
 x                   -x
ℯ  + 2⋅cos(x) - 6 + 2  

Note the different script for e.

In [21]: fdiff=Derivative(func, x)
In [22]: fdiff
Out[22]: 
d ⎛ x                   -x⎞
──⎝ℯ  + 2⋅cos(x) - 6 + 2  ⎠
dx                         
In [23]: fdiff.doit()
Out[23]: 
 x               -x       
ℯ  - 2⋅sin(x) - 2  ⋅log(2)
In [24]: fdiff.doit().subs({x:.4})
Out[24]: 0.712988013023969 - 0.757858283255199⋅log(2)
In [25]: N(fdiff.doit().subs({x:.4}))
Out[25]: 0.187680680721628

With your expression

In [14]: func
Out[14]: 
 x                   -x
e  + 2⋅cos(x) - 6 + 2  
In [15]: func.free_symbols
Out[15]: {e, x}

To use this, you have to include both e and x in the subs.

In [38]: e=list(Out[15])[0]