Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #70717 > unrolled thread
| Started by | Vlastimil Brom <vlastimil.brom@gmail.com> |
|---|---|
| First post | 2014-04-29 18:18 +0200 |
| Last post | 2014-04-29 18:18 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Significant digits in a float? Vlastimil Brom <vlastimil.brom@gmail.com> - 2014-04-29 18:18 +0200
| From | Vlastimil Brom <vlastimil.brom@gmail.com> |
|---|---|
| Date | 2014-04-29 18:18 +0200 |
| Subject | Re: Significant digits in a float? |
| Message-ID | <mailman.9574.1398788304.18130.python-list@python.org> |
2014-04-28 18:00 GMT+02:00 Roy Smith <roy@panix.com>:
> 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.
>
> ---
> Roy Smith
> roy@panix.com
>
Hi,
I doubt, many would consider a string/regex approach very clean here,
but anyway; hopefully the results conform to your specs (as far as I
understood it correctly). Alternatively, the floats can be rounded
before, if e.g. 39.9999999 could be a false positive for 4-digits
precision.
hth,
vbr
= = = = = = =
>>> for fl in (38.0, 41.2586, 40.75280000000001, 49.25, 33.795199999999994, 36.837199999999996, 34.1489, 45.5, 40.0010, 39.00000009, 39.9999999, 38.00009, 40.0100, 41.2000, 43.0001):
... print repr(fl), "==>", len(re.match(r"^-?\d+\.([0-9]{0,4})(?<!0)",
str(fl)).group(1))
...
38.0 ==> 0
41.2586 ==> 4
40.75280000000001 ==> 4
49.25 ==> 2
33.795199999999994 ==> 4
36.837199999999996 ==> 4
34.1489 ==> 4
45.5 ==> 1
40.001 ==> 3
39.00000009 ==> 0
39.9999999 ==> 4
38.00009 ==> 0
40.01 ==> 2
41.2 ==> 1
43.0001 ==> 4
>>>
= = = = = = =
Back to top | Article view | comp.lang.python
csiph-web