Difference between revisions of "Pint"

From wiki
Jump to navigation Jump to search
(Created page with "Category:Python This code make all kind of units available as UNITS.unit: <syntaxhighlight lang=python> import pint UNITS = pint.UnitRegistry() Quantity = UNITS.Quantity...")
 
 
Line 7: Line 7:
 
Quantity = UNITS.Quantity
 
Quantity = UNITS.Quantity
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
To see all units available open the python shell:
 +
 +
<code>>>> UNITS.</code> and press <tab> twice. To limit the list type the first character(s) of the unit <code>>>> UNITS.a</code>
  
 
You can specify formulas with units.
 
You can specify formulas with units.
Line 22: Line 26:
 
Output:
 
Output:
 
<code>88.2 meter / second</code>
 
<code>88.2 meter / second</code>
 +
 +
;unitaval.to(UNITS.unitb)
 +
:Convert the unita to unitb
 +
:Conversion of compatible units is on the fly. The first unit in the calculation defines the output unit.
 +
Example:
 +
<syntaxhighlight lang=python>
 +
distance = 15 * meter
 +
distance.to(UNITS.yard)
 +
</syntaxhighlight>
 +
Output:
 +
<code><Quantity(16.404199475065617, 'yard')></code>

Latest revision as of 23:09, 5 December 2018


This code make all kind of units available as UNITS.unit:

import pint
UNITS = pint.UnitRegistry()
Quantity = UNITS.Quantity

To see all units available open the python shell:

>>> UNITS. and press <tab> twice. To limit the list type the first character(s) of the unit >>> UNITS.a

You can specify formulas with units.

The formula for gravity acceleration:

meter = UNITS.meter
second = UNITS.second
acc = 9.8 * meter / second ** 2

time = 9 * second
speed = acc * time
print(speed)

Output: 88.2 meter / second

unitaval.to(UNITS.unitb)
Convert the unita to unitb
Conversion of compatible units is on the fly. The first unit in the calculation defines the output unit.

Example:

distance = 15 * meter
distance.to(UNITS.yard)

Output: <Quantity(16.404199475065617, 'yard')>