Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm having an issue with determining if a variable is an integer. Not the variable type, but the actual value stored in the variable. I have tried using variable % 1 as a test, but it does not seem to work. Here is the code I'm using for the test:

if ((xmax - x0)/h) % 1 == 0:
    pass
elif ((xmax - x0)/h) % 1 != 0:
    print "fail"

No matter what values are present for xmax, x0, and h, the statement always passes. For example, if they are 2.5 (2.5 % 1 = .5), it will still pass. I have tried if/else so i tried an else if statement as above and it does not work either.

share|improve this question
2  
Use int(x) == x –  MostafaR May 16 '13 at 4:52
    
Thanks, this is the simplest of the answers. Can't believe I didn't think of it before! –  danielu13 May 16 '13 at 5:09
    

3 Answers 3

up vote 0 down vote accepted

To find out whether a float number has integer value, you could call .is_integer() method:

>>> 2.0 .is_integer()
True
>>> 2.5 .is_integer()
False

If xmax, x0, h are int instances then to test whether (xmax - x0) is evenly divisible by h i.e. whether the result of truediv(xmax - x0, h) is an integer:

if (xmax - x0) % h == 0:
    pass

For float values, use math.fmod(x, y) instead of x % y to avoid suprising results:

from math import fmod

if fmod(xmax - x0, h) == 0:
    pass

In most cases you might want to compare with some tolerance:

eps = 1e-12 * h
f = fmod(xmax - x0, h)
if abs(f) < eps or abs(f - h) < eps:
    pass

The result of fmod is exact by itself but the arguments may be not therefore the eps might be necessary.

share|improve this answer
    
Wow, I didn't know of these methods that are much easier. Thanks! –  danielu13 May 18 '13 at 2:12

If both sides of the / are int, the result will be too - at least in Python 2.x. Thus your test for an integer value will always be true.

You can convert one side or the other to float and it will give a floating point result:

if (float(xmax - x0)/h) % 1 == 0:

You can also import the behavior from Python 3 that always returns a floating point result from a division:

from __future__ import division
share|improve this answer

its simple...

if isinstance(var, int):
    pass
else:
    fail
share|improve this answer
    
Test it for var = 2.0, is it working? –  MostafaR May 16 '13 at 4:52
    
I tested it in a python shell and it returns False for 2.0. In my script, however, it always returns true whether it would be 2.0 or 2.5. None of the other methods are working inside of my script either. EDIT: I just didn't notice where it was printing fail. –  danielu13 May 16 '13 at 5:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.