How to write string (float) to file?

Bengt Richter bokr at accessone.com
Wed Aug 29 03:04:15 EDT 2001


On Wed, 29 Aug 2001 00:11:39 -0400, "Steve Holden" <sholden at holdenweb.com> wrote:

>"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.
>>
Sorry about the pedantry. I just flashed into my representation thing ;-)
>>
>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.
>
But following your rule (snipped from prev post):

>... round up if the digit before 5 is evan, down if it's odd. Since this is
>almost 30 years on, I'm sure you'll forgive me if I'm wrong).

Sorry, my post text placement looked, in retrospect, like I was responding
to your phrase about forgiving you if you were wrong (which I would, but I
wasn't sure of the rule without looking it up, which I still haven't ;-).

I was trying to point out that the actual number behind '0.015' doesn't have
a '5' to apply your rule with. So it's either accidental that the result coincided
or there is a Timotheotic adjustment being made prior to the rule application;-)

>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?
>
Nothing. I advocated it in my other post ;-)

>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
I don't. I think you're thinking of Rainer ;-)

>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.
>
Yes, it would take too long to decide what constituted better ;-)




More information about the Python-list mailing list