Significant digits in a float?

Ned Batchelder ned at nedbatchelder.com
Mon Apr 28 12:07:14 EDT 2014


On 4/28/14 12:00 PM, Roy Smith wrote:
> Fundamentally, these numbers have between 0 and 4 decimal digits of precision, and I want to be able to intuit how many each has, ignoring the obvious floating point roundoff problems.  Thus, I want to map:
>
> 38.0  ==> 0
> 41.2586 ==> 4
> 40.75280000000001 ==> 4
> 49.25 ==> 2
> 33.795199999999994 ==> 4
> 36.837199999999996 ==> 4
> 34.1489 ==> 4
> 45.5 ==> 1
>
> Is there any clean way to do that?  The best I've come up with so far is to str() them and parse the remaining string to see how many digits it put after the decimal point.

That sounds like a pretty clean way:  len(str(num).partition(".")[2]), 
though it also sounds like you understand all of the inaccuracies in 
that technique.

-- 
Ned Batchelder, http://nedbatchelder.com




More information about the Python-list mailing list