Reputation: 31
This is my code:
num = math.log(536870912) / math.log(2) # num = 29.0
ceil = math.ceil(num)
floor = math.floor(num)
print(ceil, floor)
The output is (30.0, 29.0)
My question is when I just print math.ceil(29.0) the result is 29.0, why the above code gives me the 30.0 as ceiling?
Upvotes: 2
Views: 376
Reputation: 1020
I could say because
math.log(536870912) / math.log(2) = 29.000000000000004
And
29.000000000000004 != 29.0
As usr2564301 points out, floating point math is inaccurate.
Upvotes: 1
Reputation: 27567
Because num does not equal to 29.0 exactly. If you print it, you will get something like 29.000000000000004:
import math
num = math.log(536870912) / math.log(2) # num = 29.0
print(num)
ceil = math.ceil(num)
floor = math.floor(num)
print(ceil, floor)
Output:
29.000000000000004
30 29
You can check out this article for more details.
Upvotes: 1
Reputation: 768
This is due to the inaccuracies of floating point math in python.
Print the number too:
import math
num = math.log(536870912) / math.log(2) # num = 29.0 (not actually)
ceil = math.ceil(num)
floor = math.floor(num)
print(num, ceil, floor)
29.000000000000004 30 29
ceil()
will return the the next highest integer.
I suggest using round()
Upvotes: 3