How to write string (float) to file?

Steve Holden sholden at holdenweb.com
Wed Aug 29 00:43:32 CEST 2001


"Rainer Deyke" <root at rainerdeyke.com> wrote in message
news:x5Ui7.53338$c8.23437612 at news1.denver1.co.home.com...
> "Tim Peters" <tim.one at home.com> wrote in message
> news:mailman.999028783.18165.python-list at python.org...
> > [Tim]
> > > ...
> > > My bet is the poster would rather, e.g., see '0.67' than '0.66' given
> > > a=2 and b=3.  If you're going to fake fp by hand, then you're
> > > responsible for faking all of it, incl. sensible rounding.
> >
> > [Rainer Deyke]
> > > c = (((a * 200) / b) + 1) / 2
> > > s = '%03d' % c
> > > file.write(s[:-2] + '.' + s[-2:])
> >
> > So that, e.g., 1/200 rounds to '0.01', but (-1)/200 rounds to '0.00' and
> > loses the minus sign?  '%.2f' looks better all the time <0.2f wink>.
>
> If you're that picky about accuracy, floats are definitely the wrong
choice.
>
Wrong. Tim isn't being picky about accuracy, he's being picky about
correctly rounding numbers to the required number of decimal places. If a
number is 6.66666 (plus or minus noise beyond ten decimal places) there is
no system which makes 6.66 the correct answer to 2 D.P.

> >>> '%.2f' % (0.005)
> '0.01'
> >>> '%.2f' % (0.015)
> '0.01'
> >>> '%.2f' % (0.025)
> '0.03'
>
Perfect, and just what a numerical analyst would require: alternate cases
that are exactly at the midpoint round in opposite directions. [Thouhg in
fact it's a bit lucky, and I seem to remember the rule I was taught back in
the days when you did this sort of thing on a motor-driven calculator said
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).

> If you want symmetry about 0, that's easy enough:
>
> c = (((abs(a) * 200) / abs(b)) + 1) / 2
> if a < 0: c = -c
> if b < 0: c = -c
> s = '%03d' % c
> file.write(s[:-2] + '.' + s[-2:])
>
> But why stop there?  Why not use accountant rounding (i.e. when rounding
to
> the nearest multiple of N, if a number is exactly between two multiples of
> N, pick the one which is a multiple of 2 * N)?
>
> c / (a * 100) / b
> n = (a * 100) % b
> if n * 2 > b: c += 1
> elif n * 2 == b:
>   c += (c & 1)
> s = '%03d' % c
> file.write(s[:-2] + '.' + s[-2:])
>
>
Alternately, and more to the point, why go to all these lengths when the
implementors of Python have given us the perfectly reasonable string format
feature that Tim keep politely suggesting you use :-)

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








More information about the Python-list mailing list