# 如何在Python中将度量及其误差估计四舍五入为指定数量的有效数字？

[英]How would I round a measurement and its error estimate to a specified number of significant figures in Python?

I want a function that given a measurement and the error estimate, will round the error to a specified number of significant figures, and round the measurement value to the corresponding digit. 我想要一个给出测量值和误差估计的函数，将误差四舍五入到指定数量的有效数字，并将测量值四舍五入到相应的数字。 Here is an example of inputs and expected outputs: 这是输入和预期输出的示例：

``````>>> g = 6.6740813489701e-11
>>> g_err = 0.0003133212341e-11
>>> round_sig_figs(g, g_err, sig_figs=2)
(6.67408e-11, 3.1e-15)
``````

Typically errors are reported with 2 significant figures. 错误通常以2个有效数字来报告。 I want a function that will return a value's error estimate with this level of precision and also truncate the value to the correct decimal place. 我想要一个函数，该函数将以这种精度返回值的错误估计，并且还将值截断为正确的小数位。

``````import numpy as np

def round_sig_figs(val, val_err, sig_figs=2):
'''
Round a value and its error estimate to a certain number
of significant figures (on the error estimate).  By default 2
significant figures are used.
'''

n = int(np.log10(val_err))  # displacement from ones place
if val_err >= 1:
n += 1

scale = 10 ** (sig_figs - n)
val = round(val * scale) / scale
val_err = round(val_err * scale) / scale

return val, val_err
``````

Here is the listed example: 这是列出的示例：

``````>>> g = 6.6740813489701e-11
>>> g_err = 0.0003133212341e-11
>>> round_sig_figs(g, g_err)
(6.67408e-11, 3.1e-15)
``````

Here is an example of a value larger than one but rounding in the decimal places: 下面是一个值的示例，该值大于1但四舍五入到小数位：

``````>>> g_earth = 9.80665
>>> g_earth_err = 0.042749999
>>> round_error(g_earth, g_earth_err)
(9.807, 0.043)
``````

Here is an example of a value much larger than one: 这是一个比一个大得多的值的示例：

``````>>> r = 6371293.103132049
>>> r_err = 14493.004419708
>>> round_error(r, r_err)
(6371000.0, 14000.0)
``````

Python has an built-in function to achieve this: Python具有内置功能来实现此目的：

``````round(num, ndigits)
``````