MrLeeh
MrLeeh

Reputation: 5589

How to convert unit prefixes in Sympy

I would like to know how to convert a sympy value with a physical unit into the same unit with another prefix. For example:

>>> import sympy.physics.units as u
>>> x = 0.001 * u.kilogram
0.001kg

should be converted to grams. The approach I have taken so far is very bloated and delivers a wrong result.

>>> x / u.kilogram * u.gram
1.0^-6kg

It should be 1g instead.

Upvotes: 1

Views: 1571

Answers (2)

Dirk Helgemo
Dirk Helgemo

Reputation: 59

>>> u.convert_to(x, u.gram)
1.0*gram

Upvotes: 2

kennytm
kennytm

Reputation: 523614

If you can accept printing 1 instead of 1g, you could just use division:

>>> x / u.g
1.0

Otherwise, you'd better switch to sympy.physics.unitsystems.

>>> from sympy.physics.unitsystems import Quantity
>>> from sympy.physics.unitsystems.systems import mks
>>> Quantity(0.001, mks['kg'])
0.001kg
>>> _.convert_to(mks['g'])
1g

Upvotes: 2

Related Questions