butterwagon
butterwagon

Reputation: 499

How to concisely get the units of a Sympy expression

I'm working with Sympy expressions that have units. Here's a trivial example:

from sympy.physics.units import newton, meter
atmosphere = 101325. * newton / (meter **2)

In the above example, is there a concise way to get the units, i.e. newton / (meter **2) from the variable atmosphere?

Upvotes: 3

Views: 1555

Answers (2)

butterwagon
butterwagon

Reputation: 499

I'm thinking the right answer for my application is actually expr.as_coeff_Mul(), which returns the tuple (c, x) where c is a number and x is a product of symbols. If your expression is only numbers and units, this will give you (magnitude, units) directly.

Upvotes: 2

user6655984
user6655984

Reputation:

Your approach is good, but I would replace the check for is_number with has(Quantity)

from sympy.physics.units import Quantity,
def unit(expr):
    return expr.subs({x: 1 for x in expr.args if not x.has(Quantity)})

Then it works also with symbolic amounts, like

g = symbols('g')
acc = g*meter/second**2
unit(acc)  # meter/second**2 

Upvotes: 2

Related Questions