Robert Lennon
Robert Lennon

Reputation: 11

Python integer testing

def isinteger(x):
    while x > 0.0:
        x = x - 1.0
    if x < 0.0:
        return 0.0
    elif x == 0:
        return 1.0

d = input('')
print isinteger(d)

The code is somewhat self explanatory. I'm using it for a fractran interpreter. Here is my problem: I input a fraction, such as 22/7, and I get a 1 as my output. Does it have something to do with python's IO?

Upvotes: 1

Views: 954

Answers (5)

Tony Veijalainen
Tony Veijalainen

Reputation: 5555

If you want to check for integer for example for finding big perfect squares, you must consider inaccuracy of binary representations (abs is not needed for positive numbers, but is needed for negative numbers):

x = -190.00000000001
print int(x) == x

epsilon = 1E-10

def isinteger(n):
    " near enoungh to pass as integer considering round of errors "
    return abs(n-int(n)) < epsilon

print isinteger(x)

Implied eval of Python2 is considered too powerfull to be safe. If you want to input numbers instead of let user to give any formula (and in every case you need to add try...except handling for the users input):

number = raw_input('Give number: ')
number = int(number) if all(c.isdigit() for c in number) else float(number)
print number

Upvotes: 1

Vivek S
Vivek S

Reputation: 5550

your inputs are both integers so it results in giving 3 as input thereby it produces 1 as output.

Upvotes: 0

phooji
phooji

Reputation: 10395

22.0/7 vs 22/7 aside, there is another problem with this approach: it does not work in the majority of programming languages, because of the way floating point numbers are represented. For example, using your original function:

In [37]: isinteger(190.000000000000000001)
Out[37]: 1.0

Using Sean's int(x) == x suggestion:

In [39]: x = 190.000000000000000001
In [40]: int(x) == x
Out[40]: True

I realize it doesn't directly address the question, but I hope it will prevent a future one :)

Upvotes: 2

Sean
Sean

Reputation: 3062

If you're using python 2, inputting "22/7" directly leads to integer division, i.e. it rounds your input down to 3, thus the algorithm returns 1. Try inputting 22.0/7 instead.

Also, you might want to consider faster alternatives to this algorithm if you're using it for anything real. Possibilities:

def isinteger(x):
    return int(x) == x

def isinteger(x):
    return isinstance(x, int)

Upvotes: 2

srgerg
srgerg

Reputation: 19329

The input function evaluates your 22/7 exactly the same way as if it had been entered into the python interpreter. Since both 22 and 7 are integers you get an integer division with a result of 3. If you want float division, enter either 22.0/7 or 22/7.0 both of which result in 3.146....

Upvotes: 5

Related Questions