python - sympy.physical.units 替换给出 TypeError

标签 python python-3.x sympy

我尝试使用 sympy 作为某些转换/数学代码的后端,但遇到了这个问题。

from sympy.parsing.sympy_parser import parse_expr
from sympy.physics import units

type(units.newton) # -> sympy.physics.units.quantities.Quantity

parse_expr('2*Newton').subs({'Newton':units.newton}) # -> 2N
parse_expr('2*newton').subs({'newton':units.newton}) # -> 2N
parse_expr('2*n').subs({'n':units.newton}) # -> 2N
parse_expr('2*N').subs({'N':units.newton}) # -> raises TypeError below
parse_expr('N').subs() # -> raises AttributeError below
parse_expr('N') # -> <function sympy.core.evalf.N(x, n=15, **options)>

类型错误:* 不支持的操作数类型:“整数”和“函数”

AttributeError:“function”对象没有属性“subs”

看来 sympy 替代了 evalf.N 函数而不是提供的units.newton。是否有可以调整的替换顺序,或者从替换选项中删除“N”函数的方法?

编辑:已验证 evalf.N

使用的是 evalf.N 函数,但阻止 if 被使用似乎是一个问题。尝试使用 .subs(..., global_dict=...) 对错误没有影响。

parse_expr('N') is sympify('N') # -> True
sympify('N') is evalf.N # -> True

最佳答案

根据文档 parse_expr 采用可选参数:

global_dict : dict, optional

    A dictionary of global variables. By default, this is initialized with 
    from sympy import *; provide this parameter to override this behavior 
    (for instance, to parse "Q & S").

from sympy import * 将函数 N 引入全局 nampespace,parse_expr() 在解析 'N' 时使用该函数在你的最后三个例子中。

您可以在全局命名空间中重新定义“N”:

N = units.newton
parse_expr('2*N')  -> 2*newton

如果您无法重新定义“N”,则复制 globals(),修改该副本,然后将其传递给 parse_expr():

globals_with_units = dict(globals())
globals_with_units['N'] = units.newton

parse_expr('2*N', global_dict=globals_with_units)  -> 2*newton

parse_expr() 还采用 local_dict 参数:

local_dict : dict, optional

    A dictionary of local variables to use when parsing.

它可用于覆盖全局命名空间中“N”的定义。

parse_expr('2*N', local_dict={'N':units.newton})  -> 2*newton

关于python - sympy.physical.units 替换给出 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56812810/

相关文章:

python - 在 Python 中重现一个 C 函数指针数组

python - python 中的计算时间非常长

python - 如何在ANN中再添加一层隐藏层?并且精度低

python - 访问列表特定数字元素的列表并使用 python 合并

python - 用 sympy 替换函数调用

python - SymPy 中的维度分析

sympy - IPython Notebook Sympy 数学渲染

创建具有对象创建限制的工厂的 Pythonic 方式

python - itertools.product 消除重复元素

python - 检查输入是否为有效的罗马数字