2

In python, I have a number: U = 0.02462631224438585 +- 3.350971888120506e-06.

How do I round it to the correct significant figures due to the uncertainty being rounded to 1s.f.? Is there an easy way of using numpy? Or scipy or are the built-in function the best for this?

I've tried using set_printoptions(precision=3) but this doesn't work. I've also tried using round(number, significant - len(str(number))), but this seems long-winded.

I'm sure I have used a function that is simply a couple of years ago without having to create my own.

The final number should be U = 2.4626e-02 +- 3e-06

or U = (2.4626 +- 3e-4)e-02

YusufUMS
  • 1,506
  • 1
  • 12
  • 24
hi hi
  • 21
  • 3
  • 1
    Do you mean you want it *printed* in that way, while retaining the value originally stored in data, or do you actually want to truncate the variable? – gmds Apr 06 '19 at 10:30
  • On my phone so I can't give a full answer but you should look at the [`decimal`](https://docs.python.org/3/library/decimal.html) package. It supports exact floating point arithmetic and rounding for precision. – Andrew F Apr 06 '19 at 10:34
  • I'm putting it into a dictionary but I'm being assessed on the uncertainty so it has to be the actual variable that changes – hi hi Apr 06 '19 at 11:11

1 Answers1

3

the uncertainties module has the capability of computing the number of significant digits

import uncertainties
a = uncertainties.ufloat(0.02462631224438585, 3.350971888120506e-06)
print(a)
# 0.0246263+/-0.0000034

the defaut is two significant digits, however there is a format key for controlling the output

print('{:.1u}, {:.3uf}, {:.2uL}, {:0.2ue}'.format(a,a,a,a))
# 0.024626+/-0.000003, 0.02462631+/-0.00000335, 0.0246263 \pm 0.0000034, (2.46263+/-0.00034)e-02
PhMota
  • 163
  • 1
  • 6