简体   繁体   中英

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

This function accomplishes this task but if there is a more Pythonic method please add another answer.

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:

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

round(num, ndigits)

See: https://docs.python.org/2/library/functions.html#round

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM