首页 > 解决方案 > Sympy 演算:在评估 sympy 表达式时,python 输出 log(2) 和 e^0.3 作为符号,而不是计算它们的值

问题描述

所以我必须编写一个 python 脚本来使用牛顿法查找函数的根,并且我的代码在计算某个点的导数时不计算浮点数,它只计算 sin(x) 部分,留下 e^x和 log(2) 原样。我被卡住了,请帮忙。到目前为止,这是我的代码:

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 也不起作用, subs(x, 0.4) 也不起作用

标签: pythonsympyderivativecalculusevalf

解决方案


使用E而不是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  

注意不同的脚本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

用你的表情

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

要使用它,您必须在 subs中包含e和。x

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

推荐阅读