例如,假设我通过计算得到了这些数字:
17.969860 不确定 5.966e-05
0.01202,不确定性 0.001749
我想用这种方式格式化它们:
17.96986(6), 0.012(2)
是否存在任何类型的函数可以通过这种方式自动格式化具有不确定性的测量值?
谢谢你。
不,你必须自己编码:
import math
def str_with_err(value, error):
digits = -int(math.floor(math.log10(error)))
return "{0:.{2}f}({1:.0f})".format(value, error*10**digits, digits)
print str_with_err(17.969860, 5.966e-05)
# 17.96986(6)
print str_with_err(0.01202, 0.001749)
# 0.012(2)
uncertainties包是一个用于处理错误传播的已建立的包。正如您所描述的,它还支持格式化值/不确定性对。
from uncertainties import ufloat
print(f'{ufloat(17.969860, 5.966e-05):.1uS}')
# 17.96986(6)
print(f'{ufloat(0.01202, 0.001749):.1uS}')
# 0.012(2)
我正在开发一个轻量级的软件包,专门用于科学数字格式化,称为 sciform,它也可以执行此格式化
from sciform import SciNum
print(f'{SciNum(17.969860, 5.966e-05):!1()}')
# 17.96986(6)
print(f'{SciNum(0.01202, 0.001749):!1()}')
# 0.012(2)
或使用格式化程序对象(它公开更多选项,并且可能比使用格式规范迷你语言更具可读性):
from sciform import Formatter
sform = Formatter(
paren_uncertainty=True,
ndigits=1,
)
print(sform(17.969860, 5.966e-05))
# 17.96986(6)
print(sform(0.01202, 0.001749))
# 0.012(2)
我编写了这个函数,它应该处理所有情况,并且不依赖于除
numpy
之外的外部模块。
请注意,它不符合@drgrujic的评论“如果错误以'1'开头,那么它应该四舍五入到两位数”因为这不是我喜欢的,但可以指定错误精度。
import numpy as np
def value_with_error(val, err, precision=2):
"""String with value and error in parenthesis with the number of digits given by precision."""
# Number of digits in the error
err_decimals = precision - int(np.floor(np.log10(err) + 1))
# Output error with a "precision" number of significant digits
err_out = err - err % 10**(-err_decimals)
# Removes leading zeros for fractional errors
if err_out < 1:
err_out = int(round(err_out * 10**err_decimals))
err_format = 0
else:
err_format = int(np.clip(err_decimals, 0, np.inf))
# Format the value to have the same significant digits as the error
val_out = round(val, err_decimals)
val_format = int(np.clip(err_decimals, 0, np.inf))
return f'{val_out:.{val_format}f}({err_out:.{err_format}f})'