Alex Rivera | Logout

Determining whether an value is a whole number in Python

Asked 2011-06-04T23:17:37.733
21

I would like to determine if a numeric value in Python is a whole number. For example, given:

y = x / 3

I want to distinguish between values of x which are evenly divisible by 3 those which are not.

Edit
Report

1 Answer

4

Edit: As Ollie pointed out in the comment below this post, is_integer is part of the standard library and should therefore not be reimplemented as I did below.

This function uses the fact that every other whole number will have at least one number divisible by two with no remainder. Any non-zero fractional representation in either n or n+1 will cause both n%2 and (n+1)%2 to have a remainder. This has the benefit that whole numbers represented as float values will return True. The function works correctly for positive and negative numbers and zero as far as I can determine. As mentioned in the function, it fails for values very close to an integer.

def isInteger(n):
    """Return True if argument is a whole number, False if argument has a fractional part.

    Note that for values very close to an integer, this test breaks. During
    superficial testing the closest value to zero that evaluated correctly
    was 9.88131291682e-324. When dividing this number by 10, Python 2.7.1 evaluated
    the result to zero"""

    if n%2 == 0 or (n+1)%2 == 0:
        return True
    return False
answered 2011-10-31T14:23:52.420

Your Answer