组合和定义单位#
基本示例#
可以使用常规的Python数字操作符将单位和数量组合在一起:
>>> from astropy import units as u
>>> fluxunit = u.erg / (u.cm ** 2 * u.s)
>>> fluxunit
Unit("erg / (s cm2)")
>>> 52.0 * fluxunit
<Quantity 52. erg / (s cm2)>
>>> 52.0 * fluxunit / u.s
<Quantity 52. erg / (cm2 s2)>
分数次幂#
单位支持分数幂,在复杂的运算中保持其精度。要执行此操作,建议使用 fractions.Fraction 对象::
>>> from fractions import Fraction
>>> Franklin = u.g ** Fraction(1, 2) * u.cm ** Fraction(3, 2) * u.s ** -1
备注
与分母小于10的分数有效相同的浮点幂被隐式转换为 Fraction 发动机罩下的物体。因此,以下是等效的:
>>> x = u.m ** Fraction(1, 3)
>>> x.powers
[Fraction(1, 3)]
>>> x = u.m ** (1. / 3.)
>>> x.powers
[Fraction(1, 3)]
定义单位#
用户可以自由定义新单位,无论是基本单位还是复合单位 def_unit() 功能::
>>> bakers_fortnight = u.def_unit('bakers_fortnight', 13 * u.day)
添加一个字符串将为新单元指定一个名称,该名称将在打印该单元时显示:
>>> 10. * bakers_fortnight
<Quantity 10. bakers_fortnight>
创建一个新的基本单元也是可能的:
>>> titter = u.def_unit('titter')
>>> chuckle = u.def_unit('chuckle', 5 * titter)
>>> laugh = u.def_unit('laugh', 4 * chuckle)
>>> guffaw = u.def_unit('guffaw', 3 * laugh)
>>> rofl = u.def_unit('rofl', 4 * guffaw)
>>> death_by_laughing = u.def_unit('death_by_laughing', 10 * rofl)
>>> (1. * rofl).to(titter)
<Quantity 240. titter>
用户可以看到单元的定义及其 decomposition 通过:
>>> rofl.represents
Unit("4 guffaw")
>>> rofl.decompose()
Unit("240 titter")
默认情况下,不会通过以下方法搜索自定义单位 find_equivalent_units() 。但是,可以通过调用 add_enabled_units() **
>>> kmph = u.def_unit('kmph', u.km / u.h)
>>> (u.m / u.s).find_equivalent_units()
There are no equivalent units
>>> u.add_enabled_units([kmph])
<astropy.units.core._UnitContext object at ...>
>>> (u.m / u.s).find_equivalent_units()
Primary name | Unit definition | Aliases
[
kmph | 0.277778 m / s | ,
]
如果定义了启用了前置单元,则也必须显式启用前置单元,例如,通过使用 namespace 论点::
>>> new_units = dict()
>>> foo = u.def_unit(['Fo', 'foo'], prefixes=True, namespace=new_units)
>>> u.add_enabled_units(new_units)
<astropy.units.core._UnitContext object at ...>
现在,可以解析前缀单元等::
>>> print(u.Unit("megafoo").find_equivalent_units())
Primary name | Unit definition | Aliases
[
Fo | irreducible | foo ,
]
>>> print(u.Unit("megafoo").to(u.Unit("kFo")))
1000.0