Rounding errors to 1 significant figure and round values according to number of digits in errors

python

Solution

All you need to do is modify the function to take in a second number to let it know where to round it to.

def round_to_reference(x, y):
    return round(x, -int(floor(log10(y))))

Putting it all together, you could do something like this:

errors_r = map(round_to_1, errors)
params_r = map(round_to_reference, params, errors_r)

One thing this will not do is print the numbers with the correct number of trailing zeroes. For example,

>>> round_to_reference(12.5, 0.005)
12.5
>>> round_to_reference(12.51234, 0.005)
12.512

The numbers are rounded correctly, but you'll need to do something else to turn them into strings with the correct number of significant digits.

Problem

I'm trying to write a function that will take a list of error values and the parameters associated with those errors and: - Round the error values to 1 significant figure (as established by convention) - Round the parameters values to the number of digits present in its associated errors. So for example, if I have lists that look like: ``` errors = [0.0097, 0.83, 0.05, 0.0045] params = [0.0240, 7.85, 0.75, 12.5] ``` the resulting lists after applying such a function will look like: ``` errors_r = [0.01, 0.8, 0.05, 0.005] params_r = [0.02, 7.9, 0.75, 12.500] ``` where the errors are first rounded to 1 significant digit and then the parameters rounded to whatever number of digits the errors end up having. The function below taken from this question How to round a number to significant figures in Python does a good job of rounding the errors to 1 significant digit: ``` from math import log10, floor def round_to_1(x): return round(x, -int(floor(log10(x)))) ``` To round the values in the `params` list to the number of digits in its associated errors I could use the round() function and feed it the number of decimal places in the errors after they are rounded, but I'm not sure how I could arrive at that number.

Original source

Related problems