我正在尝试学习 python 中符号操作的来龙去脉(我是初学者)。
我有以下基本代码,输出给我一个错误,告诉我它“无法将表达式转换为 float ”。
这段代码有什么问题:
from sympy import *
from math import *
def h(x):
return log(0.75392 * x)
x = symbols('x')
hprime = h(x).diff(x)
print(hprime)
最佳答案
这是 PEP-8 中所说内容的经典示例关于通配符导入:
Wildcard imports (
from <module> import *
) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools.
问题是您需要使用 sympy.log
类,但使用 math.log
相反,它适用于 float
的函数对象,而不是 Symbol
对象。
当你写作时
from sympy import *
你正在你的模块命名空间中导入所有sympy
在顶层提供的包(还有很多东西,其中很多你根本不需要),包括 sympy.log
类。
在下一条语句之后
from math import *
您正在导入 math
中的所有内容模块,包括 math.log
,它会覆盖之前导入的 sympy.log
类。
考虑到这一点,您的示例可能会这样写
import sympy
def h(x):
return sympy.log(0.485022 * x)
x = sympy.symbols('x')
h_x = h(x)
hprime = h_x.diff(x)
print(hprime)
给我们
1.0/x
P. S.:我删除了math
导入,因为在给定示例中未使用它。
关于python - 无法将表达式转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44263889/