[Python-Dev] Rounding float to int directly ... (original) (raw)

Nick Maclaren nmm1 at cus.cam.ac.uk
Wed Aug 2 11:09:30 CEST 2006


Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:

You should NOT be using binary floats for money in the first place.

Or floating-point at all, actually. But binary floating-point is definitely unsuited for such a use.

Pseudo-rounding to decimal places is not the right way to do that. The right way is to compare the difference to a tolerance.

Right. Where the tolerance should be a combination of relative and absolute accuracy. 1.0e-300 should usually be 'similar' to 0.0.

Simon Burton <simon at arrowtheory.com> wrote:

It's not even clear to me that int(round(x)) is always the nearest integer to x.

There is a sense in which this is either true or overflow occurs.

Is it always true that float(someint)>=someint ? (for positive values).

(ie. I am wondering if truncating the float representation of an int always gives back the original int).

No.

Consider 'standard' Python representations on a 64-bit system. There are only 53 bits in the mantissa, but an integer can have up to 63. Very large integers need to be rounded, and can be rounded up or down.

Please note that I am not arguing against an int_rounded() function. There is as much reason to want one as an int_truncated() one, but there is no very good reason to to want more than one of the two. int_expanded() [i.e. ceiling] is much less useful.

For people interested in historical trivia, the dominance of the truncating form of integer conversion over the rounding form seems to be yet another side-effect of the Fortran / IBM 370 dominance over the Algol / other hardware, despite the fact that most modern languages are rooted in CPL rather than Fortran. I am unaware of any technical grounds to prefer one over the other (i.e. the reasons for wanting each are equally balanced).

It all comes down to the simple question "Do we regard a single primitive for int(round()) as important enough to provide?"

I abstain :-)

Regards, Nick Maclaren, University of Cambridge Computing Service, New Museums Site, Pembroke Street, Cambridge CB2 3QH, England. Email: nmm1 at cam.ac.uk Tel.: +44 1223 334761 Fax: +44 1223 334679



More information about the Python-Dev mailing list