Reputation: 18738
In sympy.physics.units
identical units automatically simplify when they are used in equations. However, when units are different scales of the same dimension, they are not automatically simplified. For example:
from sympy.physics.units import *
(5000 * gram) / (2 * gram)
# 2500
(5 * kilogram) / (2 * gram)
# (5 * kilogram) / (2 * gram)
5 * gram + 1 * kilogram
# 5*gram + kilogram
5 * gram + 1000 * gram
# 1005*gram
1000*liter/(5000*liter)
# 1/5
1000*liter/(5*meter**3)
# 200*liter/meter**3
Is there an easy way to force unit simplification, at least in cases where the units are different scales of the same dimension?
I am looking for the same effect as using .subs()
on all the units, just automated to use the information already contained in the expression, equivalent to
((5 * kilogram) / (2 * gram)).subs({gram: gram, kilogram: 1000 * gram, ...})
Upvotes: 3
Views: 617
Reputation:
The issue of scale can be solved by print_unit_base
method of the unit system. For example,
from sympy.physics.units.systems import MKS
expr = (5 * kilogram) / (2 * gram)
new_expr = expr.xreplace({q: MKS.print_unit_base(q) for q in expr.atoms(Quantity)})
Now new_expr
is 2500.
A simpler function to use is convert_to(expr, kilogram)
(which also returns 2500) but this depends on knowing that units of mass are an issue. print_unit_base
uniformizes all units of the given unit system.
With liter
, since it's not really a prefixed-meter-cubed, we need convert_to
:
expr2 = 1000*liter/(5*meter**3)
convert_to(expr2, meter) # 1/5
Upvotes: 2