Reputation: 143
Is there a way to force Sympy to print Volts as volts instead of returning it as a composition of SI units?
MWE:
>>> import sympy.physics.units as u
>>> V = 5 * u.V
>>> print(V)
5*kg*m**2/(A*s**3)
As pointed by @rfkortekaas, I can define new units using
V = u.Unit('V','V')
And his suggestion really solves the problem in one side. However if i use
>>> I = 0.5 * u.A
>>> R = 100 * u.ohm
>>> V_R = I * R
>>> V_R
50.0*kg*m**2/(A*s**3)
I still need to V_R
to be recognized as "V
" (voltage)
Thanks to @rfkortekaas that is still helping me with the issue, now I have:
>>> V = u.Unit('V', 'V')
>>> ohm = u.Unit('ohm = V/u.A', '\Omega')
>>> R = (10 * V) / (0.5 * u.A)
>>> R
20.0*V/A
>>> V_R = (0.5 * u.A) * (10 * ohm)
>>> V_R
5.0*A*\Omega
i.e. V/A
nor A*\Omega
are been recognized as ohm
and 'V' respectively.
Upvotes: 1
Views: 1396
Reputation: 143
Just here to share how I solved my own problem. The class below holds a list of interesting units and then it is possible to parse the units from Sympy using that list.
from sympy.physics import units as u
class Electric:
units = {}
units[u.V] = 'V'
units[u.W] = 'W'
units[u.A] = 'A'
units[u.Hz] = 'Hz'
units[u.percent] = '\%'
units[u.F] = 'F'
units[u.s] = 's'
units[u.ohm] = '\Omega'
@classmethod
def identify_unit(cls, value):
for unit in cls.units.keys():
aux = value.as_coefficient(unit)
if aux:
if aux.is_number:
return aux, cls.units[unit]
return value
@classmethod
def change_factor(cls, value):
aux = abs(value[0])
if aux >= u.mega:
return value[0] / (10 ** 6), "M" + value[1]
elif aux >= u.kilo:
return value[0] / (10 ** 3), "k" + value[1]
elif aux >= 1:
return value[0], value[1]
elif aux >= u.milli:
return value[0] * (10 ** 3), "m" + value[1]
elif aux >= u.micro:
return value[0] * (10 ** 6), "\mu{}" + value[1]
else:
return value
Example of use:
>>> V_R = 2 * u.V
>>> print(V_R)
2*kg*m**2/(A*s**3)
>>> print(Electric.identify_unit(V_R))
(2, 'V')
>>> I_R = 1 * u.milli * u.A
>>> print(I_R)
A/1000
>>> print(Electric.identify_unit(I_R))
(1/1000, 'A')
>>> R = V_R / I_R
>>> print(R)
2000*kg*m**2/(A**2*s**3)
>>> a = Electric.identify_unit(R)
>>> print(a)
(2000, '\\Omega')
>>> b = Electric.change_factor(a)
>>> print(b)
(2.00000, 'k\\Omega')
Upvotes: 1
Reputation: 6494
All sympy units will be formed as the S.I. base units. So all derived units will be expressed as a compaction of the Base units according to S.I.
Base units are formed by the unit class: sympy.physics.units.Unit('ampere', 'A').
All derived units will be formed by an mathematic operation on the Base (or derived) units.
To define this in your way you can do this as follows: Ampère is already a base unitso can be used. Define volt as Unit('volt','V'). And define ohm as a devision of volt by ampere.
Unfortunately it cannot be achieved to have volt, ampere and ohm all as Base units together and get the correct units for each. This is due to the composition of the derived as Base units.
Upvotes: 2