[Tutor] Float Numbers. 98/100 returns 0.97999999999999998
Jethro Cramp
jsc_lists@rock-tnsc.com
Wed, 28 Mar 2001 17:01:21 +0800
Tim,
Thanks for the quick reply. The first section of code worked perfectly. The
second section didn't work. Will have another look at it later on.
> Yuck, yes. For long (unbounded) integers i, str(i) *used* to produce the
> letter "L" at the end, but by popular demand it no longer does.
> That's how
> you're getting burned here. Replace this block of code:
>
> def __str__(self):
> n, p = self.n, self.p
> i, f = divmod(abs(n), _tento(p))
> if p:
> frac = str(f)[:-1]
> frac = "0" * (p - len(frac)) + frac
> else:
> frac = ""
> return "-"[:n<0] + \
> str(i)[:-1] + \
> "." + frac
>
> with this:
>
> def __str__(self):
> n, p = self.n, self.p
> i, f = divmod(abs(n), _tento(p))
> if p:
> frac = str(f)
> frac = "0" * (p - len(frac)) + frac
> else:
> frac = ""
> return "-"[:n<0] + \
> str(i) + \
> "." + frac
>
> (that simply gets rid of the two instances of [:-1], which
> stripped off the
> old trailing "L" but are now deleting the last digit(!)), and all will be
> well under 2.0. Or, maybe better, replace it with this:
>
> def __str__(self):
> n, p = self.n, self.p
> i, f = divmod(abs(n), _tento(p))
> if p:
> frac = repr(f)[:-1]
> frac = "0" * (p - len(frac)) + frac
> else:
> frac = ""
> return "-"[:n<0] + \
> repr(i)[:-1] + \
> "." + frac
>
> (replacing the original "str" calls with "repr" calls -- repr(long) still
> produces an "L" at the end) and it should work fine under both.
>
> Unfortunately, I don't know of any way to get the ftp site
> updated anymore --
> it's just an archive of old code.