sprintf & round (was RE: More random python observations from a perl programmer)
Tim Peters
tim_one at email.msn.com
Fri Aug 20 01:19:00 EDT 1999
[Tom Christiansen]
> Python has a round() function, but it seems to ignore the
> IEEE rules of rounding. However, its sprintf operator doesn't:
> >>> print "int of %f is %.0f" % (1.5, 1.5)
> int of 1.500000 is 2
> >>> print round(1.5,0)
> 2.0
> >>> print "int of %f is %.0f" % (2.5, 2.5)
> int of 2.500000 is 2
> >>> print round(2.5,0)
> 3.0
Python's sprintf rounding is inherited from the platform libc's. Virtually
all systems will round 1.5 up to 2.0, but there's wide variation (even among
Unices) in what %f.0 does to 2.5. The "round" function is Python's own.
[while Christian Tismer gets ...]
> I had a look at this again. Despite the fact that the text in
> the above example is a bit misleading by "int of" where
> a round() takes place, which version of Python/architecture
> did you use? I get the expected result, see below.
>
> >>> print "round of %f is %.0f" % (1.5, 1.5)
> round of 1.500000 is 2
> >>> print round(1.5,0)
> 2.0
> >>> print "round of %f is %.0f" % (2.5, 2.5)
> round of 2.500000 is 3
> >>> print round(2.5,0)
> 3.0
> >>>
My guess is you're running on Windows. MS rounds all halfway cases up;
Tom's complaint is that under IEEE-754 to-nearest/even rules, 1.5 and 2.5
should both round to 2. Luckily, Python's will do that the instant MS's
does <wink>.
not-sure-there's-a-winner-in-arguing-over-which-language-has-the-
lamest-754-support-ly y'rs - tim
More information about the Python-list
mailing list