目的是显示多次观察的结果,而不需要 不必要的数字,即用 与给定一致的有效数字位数 不确定性。
例如,如果计算 mean=123.45
和err=0.0012345
那么
预期输出可能类似于 123450 ± 1.2 (× 10-3),其中
使用以下规则:
- 错误总是有一位或两位有效数字。如果是第一个就两个
数字是
1
(忽略前导零) - 平均值经过四舍五入以去掉不确定的数字,除了 最后一个("stop the mean at the same decade as that of the first significant (non-zero) digit in the SEM")。如有必要,会添加尾随零以显示与错误相对应的精度。
如何在 Python 中使用它:
import statistics
mean = statistics.mean(measurements)
err = statistics.stdev(measurements, mean) / len(measurements) ** 0.5
print("{} ± {} (×10<sup>{}</sup>)".format(*round_to_uncertainty(mean, err)))
问题是如何实现round_to_uncertainty(value,
uncertainty)
表达上述规则 1 和 2 的函数。
注意:术语误差、不确定性在 问题。请参阅the Guide to the Expression of Uncertainty in Measurement (GUM) 。这是 related question for R .
最佳答案
decimal
模块可用于方便地操作数字的十进制表示形式:
from decimal import Decimal
def round_to_uncertainty(value, uncertainty):
# round the uncertainty to 1-2 significant digits
u = Decimal(uncertainty).normalize()
exponent = u.adjusted() # find position of the most significant digit
precision = (u.as_tuple().digits[0] == 1) # is the first digit 1?
u = u.scaleb(-exponent).quantize(Decimal(10)**-precision)
# round the value to remove excess digits
return round(Decimal(value).scaleb(-exponent).quantize(u)), u, exponent
示例:
for mean, err in [
(123.45, 0.0012345), # 123450 ± 1.2 (×10<sup>-3</sup>)
(8165.666, 338.9741), # 82 ± 3 (×10<sup>2</sup>)
]:
print("{} ± {} (×10<sup>{}</sup>)".format(*round_to_uncertainty(mean, err)))
输入 123.45
、0.0012345
报告为 123450 ± 1.2
(×10-3)。以及 8165.666
、338.9741
根据当前问题的规则,转换为 82 ± 3 (×102)。
关于python - 报告不确定性: given a mean and the standard error,仅显示有效数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53976847/