Significant digits in a float?
Dave Angel
davea at davea.name
Mon Apr 28 15:09:15 EDT 2014
Roy Smith <roy at panix.com> Wrote in message:
> I'm using Python 2.7
>
> I have a bunch of floating point values. For example, here's a few (printed as reprs):
>
> 38.0
> 41.2586
> 40.75280000000001
> 49.25
> 33.795199999999994
> 36.837199999999996
> 34.1489
> 45.5
>
> 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.
>
> The numbers are given to me as Python floats; I have no control over that. I'm willing to accept that fact that I won't be able to differentiate between float("38.0") and float("38.0000"). Both of those map to 1, which is OK for my purposes.
>
Ignoring the unexpected terminology, you seem to be looking for
the number of decimal places, and you're not interested in 2100
==> -2
If you know something about the possible range of the numbers,
and/or you know the valid range of decimal places, then you
should convert to string in a way that will round the 3rd, 5th,
and 6th values. Then if the string has no decimal, the answer is
0. If there are any trailing zeroes, strip them. Then just count
digits after the decimal point.
Without such limits, there can be no unique algorithm, and thus
no correct code.
--
DaveA
More information about the Python-list
mailing list