1

目的是在没有不必要数字的情况下显示几个观察的结果,即显示一个具有与给定不确定性一致的有效数字数的值。

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

  1. 错误总是有一位或两位有效数字。如果第一个数字是两个1(忽略前导零)
  2. 平均值被四舍五入以丢弃除最后一个之外的不确定数字( “将平均值停止在与 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 的功能。

注意:术语错误,不确定性在问题中使用松散。请参阅测量不确定度表达指南 (GUM)。这是R 的相关问题

4

1 回答 1

3

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.0012345123450 ± 1.2 (×10 -3 )。并且8165.666,根据当前问题的规则338.9741 转换为82 ± 3 (×10 2 ) 。

于 2018-12-30T10:28:55.967 回答