python - 报告不确定性: given a mean and the standard error,仅显示有效数字

标签 python statistics uncertainty

目的是显示多次观察的结果,而不需要 不必要的数字,即用 与给定一致的有效数字位数 不确定性。

例如,如果计算 mean=123.45err=0.0012345那么 预期输出可能类似于 123450 ± 1.2 (× 10-3),其中 使用以下规则:

  1. 错误总是有一位或两位有效数字。如果是第一个就两个 数字是 1 (忽略前导零)
  2. 平均值经过四舍五入以去掉不确定的数字,除了 最后一个("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.450.0012345 报告为 123450 ± 1.2 (×10-3)。以及 8165.666338.9741 根据当前问题的规则,转换为 82 ± 3 (×102)

关于python - 报告不确定性: given a mean and the standard error,仅显示有效数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53976847/

相关文章:

Python递归函数不返回

python - 在 docker 中安装时 Pipenv 抛出错误

machine-learning - 在分类神经网络中应如何处理训练数据中的系统不确定性(向上和向下)?

python - 计算当前行与满足条件的最新行之间的差异

r - 使用 R 和 qcc 实现附加标准运行规则

python - 我正在尝试使用 numpy 模块创建和实现一个在 Python 中识别数据集中异常值的函数,不断获取 'ValueError'

r - 在 R 中访问或解析 summary() 中的元素

Python Uncertainties 模块,ufloat 无法解压变量

python - 如何用Python确定拟合参数的不确定性?

python - 如何为分水​​岭分割创建多边形