使用自动缩放SI前缀美观地打印物理量

12

我正在寻找一种优雅的方式来美化物理量,并使用最合适的前缀(例如将12300克转换为12.3千克)。一个简单的实现方法如下:

def pprint_units(v, unit_str, num_fmt="{:.3f}"):
    """ Pretty printer for physical quantities """
    # prefixes and power:
    u_pres = [(-9, u'n'), (-6, u'µ'), (-3, u'm'), (0, ''),
              (+3, u'k'), (+6, u'M'), (+9, u'G')]

    if v == 0:
        return num_fmt.format(v) + " " + unit_str
    p = np.log10(1.0*abs(v))
    p_diffs = np.array([(p - u_p[0]) for u_p in u_pres])
    idx = np.argmin(p_diffs * (1+np.sign(p_diffs))) - 1
    u_p = u_pres[idx if idx >= 0 else 0]

    return num_fmt.format(v / 10.**u_p[0]) + " " + u_p[1]  + unit_str

for v in [12e-6, 3.4, .123, 3452]:
    print(pprint_units(v, 'g', "{: 7.2f}"))
# Prints:
#  12.00 µg
#   3.40 g
# 123.00 mg
#   3.45 kg

查看了 unitsPint,我没有找到那个功能。是否还有其他更全面地排版SI单位的库(以处理特殊情况,如角度、温度等)?


不知道以下数量的预期表示应该是什么:a=4.0 a = a / 3.0 print(pprint_units(a, 'g', "{: 7.2f}"))。如果不知道,我无法给出答案。 - Serge Ballesta
@Serge: pprint_units(4./3, 'g', "{: 7.2f}") 应该输出 ' 1.33 g' - Dietrich
3个回答

10

我曾经解决过同样的问题,而且我认为我的方法更加简洁。不过没有涉及度数或温度。

def sign(x, value=1):
    """Mathematical signum function.

    :param x: Object of investigation
    :param value: The size of the signum (defaults to 1)
    :returns: Plus or minus value
    """
    return -value if x < 0 else value

def prefix(x, dimension=1):
    """Give the number an appropriate SI prefix.

    :param x: Too big or too small number.
    :returns: String containing a number between 1 and 1000 and SI prefix.
    """
    if x == 0:
        return "0  "

    l = math.floor(math.log10(abs(x)))
    if abs(l) > 24:
        l = sign(l, value=24)

    div, mod = divmod(l, 3*dimension)
    return "%.3g %s" % (x * 10**(-l + mod), " kMGTPEZYyzafpnµm"[div])

CommaCalc

这样的度数:

def intfloatsplit(x):
    i = int(x)
    f = x - i
    return i, f

def prettydegrees(d):
    degrees, rest = intfloatsplit(d)
    minutes, rest = intfloatsplit(60*rest)
    seconds = round(60*rest)
    return "{degrees}° {minutes}' {seconds}''".format(**locals())

编辑:

添加了该单位的尺寸。

>>> print(prefix(0.000009, 2))
9 m
>>> print(prefix(0.9, 2))
9e+05 m

我知道第二个输出并不太好看。您可能想要编辑格式化字符串。

编辑:

解析像 0.000009 m² 这样的输入。适用于小于10的尺寸。

import unicodedata

def unitprefix(val):
    """Give the unit an appropriate SI prefix.

    :param val: Number and a unit, e.g. "0.000009 m²"
    """
    xstr, unit = val.split(None, 2)
    x = float(xstr)

    try:
        dimension = unicodedata.digit(unit[-1])
    except ValueError:
        dimension = 1

    return prefix(x, dimension) + unit

利用负索引来获取前缀字符串的技巧不错。我花了一会儿才明白CommaCalc链接是指向你原始代码的参考。除非有人指出更全面的解决方案(例如处理更复杂的情况,如mm²),否则赏金归你所有。 - Dietrich

3
如果您有兴趣使用Pint,请查看to_compact方法。这个方法还没有被写入文档中,但我认为它可以实现您想要的功能!
以下是OP示例的实现:
import pint
ureg = pint.UnitRegistry()

for v in [12e-6, 3.4, .123, 3452]:
    print('{:~7.2f}'.format((v * ureg('g')).to_compact()))   

>>> 12.00 ug
>>> 3.40 g
>>> 123.00 mg
>>> 3.45 kg

2
< p > decimal 模块可以帮助解决问题。此外,它还可以防止浮点数的不良舍入。< /p >
import decimal
prefix="yzafpnµm kMGTPEZY"
shift=decimal.Decimal('1E24')
def prettyprint(x,baseunit):
    d=(decimal.Decimal(str(x))*shift).normalize()
    m,e=d.to_eng_string().split('E')    
    return m + " " + prefix[int(e)//3] + baseunit

print(prettyprint (12300,'g'))
>>>> '12.3 kg'

它可以调整来管理格式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接