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

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

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

``````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
``````

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

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

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

Python具有内置功能来实现此目的：

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