[Python-Dev] New math functions

Isaac Morland ijmorlan at cs.uwaterloo.ca
Wed Feb 20 17:32:54 CET 2008

On Fri, 15 Feb 2008, Mark Dickinson wrote:

> On Tue, Feb 12, 2008 at 1:52 AM, Raymond Hettinger <python at rcn.com> wrote:
>> Also, it would be useful to have a new method, float.is_integer().  This
>> would be better than the current approach where we make the
>> test:  if x == floor(x).
> How common is this test?  Given the inexact nature of floating-point
> arithmetic, checking whether a float is exactly an integer seems like
> something that one might actually want to discourage, just like comparing
> two floats for equality.

Depending on the nature of the computations that produced the float 
result, there may be no problem with the result being different from the 
mathematical result.  For example, if you are adding up a bunch of 
multiples of 1/2, a sufficient condition for an exact result is that the 
(mathematical) total of the absolute values of the numbers isn't too big.

After such a computation, meeting the given condition, checking for an 
integer result is guaranteed to be meaningful and to match what is 
mathematically wanted.

I can't say how often one needs to check a float for being an integer.  I 
believe that "x == floor(x)" is equivalent to "not (x % 1)" which also 
generalizes to checking for an exact multiple of values other than 1.

I suspect, but do not have evidence, that circumstances in which it is 
useful to check for an integer are likely to be ones in which there is a 
better-than-usual chance of getting precise float results.  How often are 
you going to check the output of sin() for being an integer?  But on the 
other hand pitfalls will occur if we, for example, replace 1/2 in my 
example with 1/10, since these are not generally representable in float 

Isaac Morland			CSCF Web Guru
DC 2554C, x36650		WWW Software Specialist

More information about the Python-Dev mailing list