is int(round(val)) safe?

Steve Holden steve at holdenweb.com
Tue Nov 23 09:20:29 EST 2004


Tim Peters wrote:

> [Peter Hansen]
> ....
> 
>>I wonder if it would be appropriate to say something along
>>the lines of '''round() returns an integer, but not an "int".'''
> 
> 
> Well, round() is a 2-argument function, whose second argument defaults
> to 0.  It's quite defensible to say that round returns an integer
> value when the second argument is 0.
> 
> 
>>Obviously the mathematicians will have something to say about
>>this.  In computers, 1.0 may not be an integer data type, but
>>I think in math it's still considered an integer.
> 
> 
> Depends on which mathematician you're talking to.  The integer 1 is
> most often defined as the set containing the empty set, or, in a
> suitably restricted set theory, with the set of all sets containing 1
> element (which is a proper class in most set theories).  A real, OTOH,
> is a godawful construction that Americans typically don't learn until
> after they've completed "calculus" and gone on to "analysis".
> 
And most of them don't understand even then. What I want to know is why 
doesn't Python 2.4 have a speedy implementation of infinite-dimensional 
Banach spaces?

> So, instead of talking to mathematicians, I advise talking to me
> <wink>.  Yes, 1.0 is an integer!  In fact, so is 1.9998e143:  all
> sufficient large floats are exact integers.  That's why, e.g.,
> math.ceil() and math.floor() return arguments like 1.9998e143
> unchanged -- such inputs are already integers.
> 
> 
>>I am most definitely not going to claim authority in this area, however,
>>since as an engineer I consider 1.0 and 1 merely "equal to a
>>first approximation". <wink>
> 
> 
> If they differ at all, then e = 1.0 - 1 must be nonzero.  Since it
> isn't, they're identical <wink>.

You can tell this by examining the behavior of something as simple (;-) 
as a Python dict:

 >>> d = {1.0: "Something",
...        1: "Something else"}
 >>> d
{1.0: 'Something else'}
 >>>

Python has known for a long time that 1.0 and 1 are the same thing. 
Note, however, that I don't believe it's guaranteed that the contents of 
d will turn out the same in different Python versions. I suppose Tim 
would be able to quote chapter and verse, given his familiarity with 
every little implementation detail of the dict.

guaranteed-to-confuse-the-confusable-ly y'rs  - steve
-- 
http://www.holdenweb.com
http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119



More information about the Python-list mailing list