如何在品脱

时间:2016-08-25 20:06:15

标签: python units-of-measurement pint

我目前正在使用Pint来处理单位和单位转化。这似乎适用于已在Pint中定义的单元,例如

>>> import pint
>>> ureg = pint.UnitRegistry()
>>> Q = ureg.Quantity
>>> a = Q(5, 'm/s')
>>> a
<Quantity(5, 'meter / second')>
>>> a.to('ft/s')
<Quantity(16.404199475065617, 'foot / second')>

我尝试define my own units,代表百分比。就单位转换而言,百分比只是无量纲分数的100倍,这就是我定义它的方式。

>>> ureg.define('percent = dimensionless * 100 = pct')
>>> a = Q(5, 'pct')
>>> a
<Quantity(5, 'percent')>

但是我似乎无法在分数('dimensionless')和'pct'之间来回转换。

>>> a.to('dimensionless')
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    a.to('dimensionless')
  File "C:\Python35\python-3.5.1.amd64\lib\site-packages\pint\quantity.py", line 263, in to
    magnitude = self._convert_magnitude_not_inplace(other, *contexts, **ctx_kwargs)
  File "C:\Python35\python-3.5.1.amd64\lib\site-packages\pint\quantity.py", line 231, in _convert_magnitude_not_inplace
    return self._REGISTRY.convert(self._magnitude, self._units, other)
  File "C:\Python35\python-3.5.1.amd64\lib\site-packages\pint\unit.py", line 1026, in convert
    return self._convert(value, src, dst, inplace)
  File "C:\Python35\python-3.5.1.amd64\lib\site-packages\pint\unit.py", line 1042, in _convert
    src_dim = self._get_dimensionality(src)
  File "C:\Python35\python-3.5.1.amd64\lib\site-packages\pint\unit.py", line 813, in _get_dimensionality
    self._get_dimensionality_recurse(input_units, 1.0, accumulator)
  File "C:\Python35\python-3.5.1.amd64\lib\site-packages\pint\unit.py", line 837, in _get_dimensionality_recurse
    self._get_dimensionality_recurse(reg.reference, exp2, accumulator)
  File "C:\Python35\python-3.5.1.amd64\lib\site-packages\pint\unit.py", line 835, in _get_dimensionality_recurse
    reg = self._units[self.get_name(key)]
KeyError: ''

我基本上喜欢做的是能够在例如“0.73”和“73%”。如何定义和使用这样的单元?

2 个答案:

答案 0 :(得分:6)

似乎GitHub问题hgrecco/pint#185涵盖了您正在描述的案例。

使用该问题中讨论的解决方法适用于Pint-0.7.2

from pint.unit import ScaleConverter
from pint.unit import UnitDefinition
import pint

ureg = pint.UnitRegistry()
Q = ureg.Quantity

ureg.define(UnitDefinition('percent', 'pct', (), ScaleConverter(1 / 100.0)))
a = Q(5, 'pct')

print a
print a.to('dimensionless')

输出:

5 percent
0.05 dimensionless

答案 1 :(得分:1)

我遇到了同样的问题,并提出了一个简单的解决方案,似乎效果很好。

import pint

ureg = pint.UnitRegistry()
ureg.define('fraction = [] = frac')
ureg.define('percent = 1e-2 frac = pct')
ureg.define('ppm = 1e-6 fraction')

print(ureg('100 pct').to('dimensionless'))
print(ureg('0.5 dimensionless').to('pct'))
print(ureg('pct').to('ppm'))
print(ureg('1e4 ppm').to('pct'))

输出:

1.0 dimensionless
50.0 percent
10000.0 ppm
0.9999999999999999 percent

(请注意在最后一行有一些舍入错误。)

我从默认的units dictionary获得了语法,其中基本单位的定义如下

# reference
gram = [mass] = g  # dimensional
radian = [] = rad  # dimensionless