gpt4 book ai didi

python - 通过自动缩放 SI 前缀来漂亮地打印物理量

转载 作者:太空狗 更新时间:2023-10-29 18:27:47 24 4
gpt4 key购买 nike

我正在寻找一种优雅的方式来使用最合适的前缀来漂亮地打印物理量(例如 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 单位(以处理角度、温度等特殊情况)?

最佳答案

我曾经解决过同样的问题。恕我直言,更优雅。不过没有度数或温度。

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

关于python - 通过自动缩放 SI 前缀来漂亮地打印物理量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29627796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com