Hi
Is there a way to check if a float is a whole number eg 10.0, 7.0 or somthing.0
I'm doing problem 5 on project eular
Mayby I have the complete wrong idea here is my code:

``````numbertobetested = 0.0
loop2 = 1
while loop2 == 1:
numbertobetested = numbertobetested+1.0
a = 0.0
loop = 1
while loop == 1:
a = a+1.0
if a <=10:
c = numbertobetested/a
if (c % 2 == 0): #This is not what I want I need to test if
if a == 10:    # c is a whole number.
print numbertobetested
loop = 0
loop2 = 0
else:
loop = 0``````

Any help will be appreciated.
Thanks

P.S sorry for hard to read codeing(coding?)

3
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by sneekula
``````def isWhole(num):
return num == int(num)``````

Works pretty well, but can fail for numbers that are really close to whole:

Test code and output

``````for ii in xrange(1,20):
f = float('3.'+'9'*ii)
print ii, f, isWhole(f)

1 3.9 False
2 3.99 False
3 3.999 False
4 3.9999 False
5 3.99999 False
6 3.999999 False
7 3.9999999 False
8 3.99999999 False
9 3.999999999 False
10 3.9999999999 False
11 3.99999999999 False
12 4.0 False
13 4.0 False
14 4.0 False
15 4.0 False
16 4.0 True
17 4.0 True
18 4.0 True
19 4.0 True``````

Legand, thanks mate works fine.

You could also use:

``````def fuzzy_equals(a, b, delta=0.0001):
"""
returns true if (b-delta) < a < (b+delta)
used for comparison of floating point numbers a and b
"""
return abs(a-b) < delta``````