python - 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) 也不起作用
解决方案
使用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]
推荐阅读
- node.js - cloudWatch 中缺少 nodejs 日志
- javascript - 如何使用自己的名称(HTML)将图像保存到 Firebase 存储?
- javascript - 如何将 vue 项目中的所有 css 和 js 文件构建为单个文件?
- javascript - 使用 jQuery 或 Javascript 获取括号内的字符串
- javascript - 分别单击每个复选框时显示输入框并存储值
- ios - 使用带有 Vision API 的 Twilio 视频视图来检测 Pose iOS Swift
- sql - SQL Server Management Studio 错误转换不存在的字符串
- c# - 使用 Nginx 和 SignalR 在 Linux 上托管 Asp.net Core
- swift - onTapGesture 仅在 ZStack 上部分工作
- angular - 具有动态数据的材料角表