How to get the float value of Sympy's physical quantity?

Question:

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)).

Asked By: wiki-fan

||

Answers:

Well, if you want to get the value without its units you could split the string. That’s the straightforward way that i can think of.

 In [1]: import sympy.physics.units as u

         a = 133.05*(u.kg/u.m)

         new_a = float(str(a).split('*')[0])

         print(new_a)

 Out[1]: 133.05
Answered By: mforpe

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])))
Answered By: laolux

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
Answered By: Tim Skov Jacobsen

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.

Case 1: You know the expression’s unit

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

Case 2: You only know which physical quantity was measured

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
Answered By: Juan Molina Riddell

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
Answered By: Juan A. Navarro
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.