How to write string (float) to file?

Steve Holden sholden at holdenweb.com
Wed Aug 29 00:11:39 EDT 2001


"Bengt Richter" <bokr at accessone.com> wrote in message
news:3b8c306d.718575126 at wa.news.verio.net...
[ ... ]
> Well, the problem is fp literals are not necessarily as exact as they
look:
>
>  >>> `0.005`
>  '0.0050000000000000001'
>  >>> `0.015`
>  '0.014999999999999999'
>  >>> `0.025`
>  '0.025000000000000001'
>
> The essential problem is transforming representations into elements of
> another set that doesn't match 1:1 all over both sets of representations.
>
>
I am quite aware of the inexactness of floating point representations. The
inexactness that bothers me (and only mildy) is the inexactness of the
answer to the original question which started this thread. Piotr, you will
remember, asked how he could represent numbers as strings to two decimal
places in a file.

There is, as has been pointed out, a perfectly Pythonic way to do this:

>>> "%.2d" % 0.005
'00'
>>> "%0.2f" % 0.005
'0.01'
>>> "%0.2f" % 0.015
'0.01'
>>> "%0.2f" % 0.025
'0.03'

Given that, in the general case, you don't know whether the
0.025000000000000001 has been generated by programmed calculation or by a
numeric literal containing exactly that value, what's wrong with the
Pythonic way?

Given that Tim Peters has been significantly involved in developing the
code, and where numerical computation (and many other things) are concerned
he has a brain the size of a planet, I don't see why you feel it is
necessary to introduce such complications into your code to do something
which is a natural one-liner. I certainly wouldn't bet money on either of us
being able to come up with anything substantially better in finite time.

[Piotr: if you're reading this, perhaps you will appreciate how an apprently
innocent question can meander off into the undergrowth and live for days.
Good question!]

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list