# 如何在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)
``````

2 个回复

``````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)
``````
2 四舍五入到任意数量的有效数字

3 四舍五入到有效数字

4 如何在Java中将数字四舍五入到6位有效数字？

5 四舍五入有效数字规则

2014-01-29 02:02:08 2 1789   vba/ excel
6 Postgresql 四舍五入到有效数字

7 在 numpy 中四舍五入到有效数字

2013-09-20 11:13:48 13 34367   numpy
8 为什么我的十进制四舍五入到 1 位有效数字？