[Tutor] Rounding to n significant digits?

Dick Moores rdm at rcblue.com
Fri Jul 2 03:37:48 EDT 2004


Alan Gauld wrote at 00:05 7/2/2004:

> > Is there something (a function?) in Python 2.3.4 that will round a
>result
> > to n significant digits, or do I need to roll my own? I don't see
>one in
> > the math module.
>
>the round() function is a builtin.
>
> > I mean something like rounding(float, n) that would do this:
> > float = 123.456789, n = 4, returns 123.5
>
> >>> round(123.45678,3)
>123.45699999999999
>
>Note that this will result in a new floating point number,
>that is you actually lose data in the process. (Which is
>why it prints out with more than 3 digits - it is a float
>with all the usual imprecision issues that floats have).
>"print"ing it instead of evaluating it will give the expected
>result of course:
>
> >>> print round(123.45678,3)
>123.457
>
>If you just want to display the number at a given precision
>but to keep the original accuracy internally use a format string
>instead.
>
> >>> print "%6.3f" % 123.456789
>123.457
>
>And of course this creates a string rounded to the nearest
>digit rather than a floating point number.

No, the 3 examples I gave are exactly what I want:
float = 123.456789, n = 4, returns 123.5
float = .000000123456789, n = 2, returns .00000012
float = 123456789, n = 5, returns 123460000

The kind of rounding to n significant digits I'm after is the kind needed 
for calculations using physical measurements, where an accuracy greater 
than n significant digits is impossible. A simple example: Let's say we 
have 2 lengths forming a 90 degree angle. We measure the sides with an 
instrument that is accurate to 3 sig. digits, and we get 9.2 meters and 
8.1 meters. The hypotenuse is the square root of the sum of their 
squares, of course. It would be absurd to say that the hypotenuse is 
12.2577  m. The only number that makes sense is 12 or possibly 12.3 m.

Dick




More information about the Tutor mailing list