Reputation: 41
For example, I have value a
.
import sympy.physics.units as u
a = 133.05*u.kg/u.m
I want to convert this physical quantity to a float value, and the only way I know is float(a/(u.kg/u.m))
.
Upvotes: 1
Views: 1065
Reputation: 11045
If you know the desired units, I've found that dividing by those and then using quantity_simplify
tends to work reliably well.
import sympy.physics.units as u
from sympy.physics.units.util import quantity_simplify
a = 133.05 * u.kg/ u.m
def extract_magnitude(expr, units):
return quantity_simplify(expr / units)
extract_magnitude(a, u.kg / u.m) # => 133.05
extract_magnitude(a, u.grams / u.centimeter) # => 1330.5
Upvotes: 0
Reputation: 15
If you know the expression's unit or physical quantity, the following is the most reliable way I've found so far to get its magnitude as float.
def to_float(expr, expr_unit):
return float(expr / expr_unit)
Example:
import sympy.physics.units as un
flow_rate = 50 * un.m ** 3 / un.h
unit = un.m ** 3 / un.h
print(to_float(flow_rate, unit))
# 50.0
https://en.wikipedia.org/wiki/List_of_physical_quantities
from sympy.physics.units import convert_to
def to_float_as(expr, unit):
converted = convert_to(expr, unit)
return to_float(converted, unit)
Example:
Let's say you have multiple measurements in multiple units, but all measure length, and you are interested in summing them.
from functools import partial
import sympy.physics.units as un
measurements = [
50 * un.m,
3 * un.km,
2.5 * un.mi,
]
sum_in_meters = sum(map(partial(to_float_as, unit=un.m), measurements))
print(sum_in_meters)
# ~7073.36
Upvotes: 0
Reputation: 3852
You can use as_coeff_Mul
like this:
>>> a = 133.05*u.kg/u.m
>>> a.as_coeff_Mul()
(133.05, kg/m)
So the float value would be
>>> a.as_coeff_Mul()[0]
133.05
Upvotes: 4
Reputation: 1565
You can use a.args
to get the required information. It returns a tuple containing first the numerical value and then the units. Example:
import sympy.physics.units as u
a = 133.05*u.kg/u.m
print(a.args[0])
print(type(float(a.args[0])))
Upvotes: 2