4

I'm trying to write a function that will take a list of error values and the parameters associated with those errors and:

  1. Round the error values to 1 significant figure (as established by convention)
  2. 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.

Community
  • 1
  • 1
Gabriel
  • 40,504
  • 73
  • 230
  • 404

1 Answers1

6

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.

Rob Watts
  • 6,866
  • 3
  • 39
  • 58
  • This is a great answer, a simple modification to the original function works like a charm. Trailing zeroes are not really a necessity so it's okay. Thank you! – Gabriel Apr 21 '14 at 23:05