How to write string (float) to file?

Rainer Deyke root at rainerdeyke.com
Tue Aug 28 20:47:29 CEST 2001


"Jeff Shannon" <jeff at ccvcorp.com> wrote in message
news:3B8BDDF2.C6DF7018 at ccvcorp.com...
>
>
> Rainer Deyke wrote:
>
> > <gbreed at cix.compulink.co.uk> wrote in message
> >
> > > c = '%.2f'%(float(a)/b)
> >
> > That's unreliable.  Use this instead:
> >
> > c = (a * 100) / b
> > s = '%03d' % c
> > file.write(s[:-2] + '.' + s[-2:])
> >
>
> Unreliable how?

You are relying in an approximation to give accurate results.  Consider the
case where 'a' is a long integer that cannot be fully represented in a
Python float.

> The bar() version, your suggestion, appears to *usually* truncate, but in
a few
> cases rounds up.

No, it always rounds to negative infinity.

>  The foo() version *always* rounds to nearest .01.

There is no such guarantee; it is merely an artifact of the implementation
and the values you chose.

>  I would
> consider the latter to be the more reliable (consistent) behavior.  (I was
> surprised by this, actually--I expected bar() to always truncate, and was
going
> to simply point out that it was a matter of whether truncation or rounding
was
> preferred...)

You are being misled by floating point errors.  If you recalculate by hand
instead of relying on floating point calculations, you will see that 'bar'
always truncates, and it is the floating point unit which is in error.  This
just demonstrates that floats are a Bad Idea if you want correctness.

If you want to round to the nearest reliably, use this:

def baz(a, b):
  s = '%03d' % (((a * 200) / b) + 1) / 2
  return s[:-2] + '.' + s[-2:]



--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor





More information about the Python-list mailing list