python - 如何简洁地获取 Sympy 表达式的单位

标签 python sympy

我正在使用具有单位的 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/

相关文章:

python - Python 中的字符串反转

python - 如何让 'pip install'不卸载其他版本?

python - 使用自定义函数迭代 Pandas 中系列中的每个项目

Python sympy.Plot - OverflowError : int too large to convert to float

python - sympy 中的索引对象到底是什么?

python - 求解线性方程组和线性不等式

python - pandas Series.cumsum() 与 pandas.expanding_sum()

python - 使用 pyparsing 从 ovs 转储流中提取数据

python - 在表达式树中查找和替换函数

python - 具有变量的矩阵的 Sympy 特征值