无法将表达式转换为浮点数
Can't convert expression to float
我正在尝试学习 python 中符号操作的来龙去脉(我是初学者)。
我有以下基本代码,输出给我一个错误,告诉我它 "can't convert expression to 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)
这是 classic 示例 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
class, but using math.log
function instead which works on float
objects, not Symbol
个对象。
写的时候
from sympy import *
你正在你的模块命名空间中导入 sympy
包在顶层提供的所有东西(还有很多东西,其中很多你根本不需要),包括 sympy.log
class.
下一条语句后
from math import *
您正在导入 math
模块中的所有内容,包括 math.log
,这会覆盖之前导入的 sympy.log
class.
考虑到这一点,您的示例可能会这样写
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
导入,因为它没有在给定的示例中使用。
这里的问题是 sympy
和 math
包都定义了一个名为 log
的函数。
将它们导入为 from sympy import *
,然后 from math import *
用 math.log
覆盖 sympy.log
。
最好始终使用 import sympy
,然后调用您的函数 sympy.log
或(如果像我一样懒惰)执行 import sympy as sym
,然后调用 sym.log
。确保对 math 包也这样做。这种方法会在以后为您省去很多麻烦,并使您的代码更容易被其他人理解。
我正在尝试学习 python 中符号操作的来龙去脉(我是初学者)。
我有以下基本代码,输出给我一个错误,告诉我它 "can't convert expression to 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)
这是 classic 示例 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
class, but using math.log
function instead which works on float
objects, not Symbol
个对象。
写的时候
from sympy import *
你正在你的模块命名空间中导入 sympy
包在顶层提供的所有东西(还有很多东西,其中很多你根本不需要),包括 sympy.log
class.
下一条语句后
from math import *
您正在导入 math
模块中的所有内容,包括 math.log
,这会覆盖之前导入的 sympy.log
class.
考虑到这一点,您的示例可能会这样写
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
导入,因为它没有在给定的示例中使用。
这里的问题是 sympy
和 math
包都定义了一个名为 log
的函数。
将它们导入为 from sympy import *
,然后 from math import *
用 math.log
覆盖 sympy.log
。
最好始终使用 import sympy
,然后调用您的函数 sympy.log
或(如果像我一样懒惰)执行 import sympy as sym
,然后调用 sym.log
。确保对 math 包也这样做。这种方法会在以后为您省去很多麻烦,并使您的代码更容易被其他人理解。