Python - pint - 我可以将默认类型设置为十进制吗?
Python - pint - Can I set default type to Decimal?
我正在项目中使用 pint 模块。 Objects 在我的项目中将数字数据处理为小数。当我将简单的 pint 单位设置为小数时,它起作用了:
>>> import pint
>>> from decimal import Decimal as D
>>> ureg = pint.UnitRegistry()
>>> D(10) * ureg.kN
<Quantity(10, 'kilonewton')>
但是,如果我尝试添加第二个单元,它就会中断。在此示例中构建千牛顿*米:
>>> D(10) * ureg.kN * ureg.m
TypeError: unsupported operand type(s) for *: 'decimal.Decimal' and 'float'
我正在使用这个技巧:
>>> a = D(1) * ureg.kN
>>> b = D(1) * ureg.m
>>> unit_kNm = a * b
>>> D(10) * unit_kNm
<Quantity(10, 'kilonewton * meter')>
我明白为什么会这样。我正在寻找一种解决方案来根据需要设置 pint。
类型转换为 decimal
import decimal
D(10) * ureg.kN * decimal.Decimal(ureg.m)
这个有效:
>>> D(10) * (ureg.kN * ureg.m)
<Quantity(10, 'kilonewton * meter')>
还有这个:
>>> Q = ureg.Quantity
>>> Q(D(10), "kN*m")
<Quantity(10, 'kilonewton * meter')>
我正在项目中使用 pint 模块。 Objects 在我的项目中将数字数据处理为小数。当我将简单的 pint 单位设置为小数时,它起作用了:
>>> import pint
>>> from decimal import Decimal as D
>>> ureg = pint.UnitRegistry()
>>> D(10) * ureg.kN
<Quantity(10, 'kilonewton')>
但是,如果我尝试添加第二个单元,它就会中断。在此示例中构建千牛顿*米:
>>> D(10) * ureg.kN * ureg.m
TypeError: unsupported operand type(s) for *: 'decimal.Decimal' and 'float'
我正在使用这个技巧:
>>> a = D(1) * ureg.kN
>>> b = D(1) * ureg.m
>>> unit_kNm = a * b
>>> D(10) * unit_kNm
<Quantity(10, 'kilonewton * meter')>
我明白为什么会这样。我正在寻找一种解决方案来根据需要设置 pint。
类型转换为 decimal
import decimal
D(10) * ureg.kN * decimal.Decimal(ureg.m)
这个有效:
>>> D(10) * (ureg.kN * ureg.m)
<Quantity(10, 'kilonewton * meter')>
还有这个:
>>> Q = ureg.Quantity
>>> Q(D(10), "kN*m")
<Quantity(10, 'kilonewton * meter')>