How to check if a float value is a whole number
--
Track title: CC F Haydns String Quartet No 53 in D
--
Chapters
00:00 Question
00:35 Accepted answer (Score 533)
02:22 Answer 2 (Score 65)
02:58 Answer 3 (Score 20)
03:11 Answer 4 (Score 13)
03:29 Thank you
--
Full question
https://stackoverflow.com/questions/2158...
Accepted answer links:
[float.is_integer()]: http://docs.python.org/library/stdtypes....
[math.isclose()]: https://docs.python.org/library/math.htm...
[mentioned in PEP485]: https://www.python.org/dev/peps/pep-0485...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #floatingpoint
#avk47
ACCEPTED ANSWER
Score 579
To check if a float value is a whole number, use the float.is_integer() method:
>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False
The method was added to the float type in Python 2.6.
Take into account that in Python 2, 1/3 is 0 (floor division for integer operands!), and that floating point arithmetic can be imprecise (a float is an approximation using binary fractions, not a precise real number). But adjusting your loop a little this gives:
>>> for n in range(12000, -1, -1):
... if (n ** (1.0/3)).is_integer():
... print n
...
27
8
1
0
which means that anything over 3 cubed, (including 10648) was missed out due to the aforementioned imprecision:
>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996
You'd have to check for numbers close to the whole number instead, or not use float() to find your number. Like rounding down the cube root of 12000:
>>> int(12000 ** (1.0/3))
22
>>> 22 ** 3
10648
If you are using Python 3.5 or newer, you can use the math.isclose() function to see if a floating point value is within a configurable margin:
>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True
For older versions, the naive implementation of that function (skipping error checking and ignoring infinity and NaN) as mentioned in PEP485:
def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
ANSWER 2
Score 20
You could use this:
if k == int(k):
print(str(k) + " is a whole number!")
ANSWER 3
Score 13
You don't need to loop or to check anything. Just take a cube root of 12,000 and round it down:
r = int(12000**(1/3.0))
print r*r*r # 10648
ANSWER 4
Score 9
You can use a modulo operation for that.
if (n ** (1.0/3)) % 1 != 0:
print("We have a decimal number here!")