我正在使用具有单位的 Sympy 表达式。这是一个简单的例子:
from sympy.physics.units import newton, meter
atmosphere = 101325. * newton / (meter **2)
在上面的示例中,是否有一种简洁的方法可以从变量 atmosphere
中获取单位,即 newton/(meter **2)
?
最佳答案
您的方法很好,但我会用 has(Quantity)
替换对 is_number
的检查
from sympy.physics.units import Quantity,
def unit(expr):
return expr.subs({x: 1 for x in expr.args if not x.has(Quantity)})
然后它也适用于符号数量,例如
g = symbols('g')
acc = g*meter/second**2
unit(acc) # meter/second**2
关于python - 如何简洁地获取 Sympy 表达式的单位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51119918/