How to write string (float) to file?
sholden at holdenweb.com
Wed Aug 29 06:11:39 CEST 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
> >>> `0.005`
> >>> `0.015`
> >>> `0.025`
> 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
>>> "%0.2f" % 0.005
>>> "%0.2f" % 0.015
>>> "%0.2f" % 0.025
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
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.
More information about the Python-list