1

The question is in the title, for example what I am worried about is:

If I calculate math.ceil(math.log(4,2)), do I have the risk of getting 3 instead of 2 because the log will return 2.0000000000000343 instead of 2.0?

I suspect not but I haven't found something to confirm it!

EugVal
  • 233
  • 1
  • 14
  • 1
    You may want to look at `int.bit_length()`: for a positive integer `n`, `math.ceil(math.log(n, 2))` is more safely computed as `(n-1).bit_length()`. Also, note that recent versions of Python have `math.log2`, which is a bit more accurate than `math.log(..., 2)`. – Mark Dickinson Jul 15 '17 at 13:34

1 Answers1

2

Yes. You can simply calculate math.ceil(math.log(x**y,x)) for many (x,y) pairs until it isn't equal to y :

>>> next((x,y) for x in range(2,100) for y in range(2,100) if y != math.ceil(math.log(x**y,x)))
(2, 29)
>>> '%.30f' % math.log(2**29,2)
'29.000000000000003552713678800501'
>>> math.ceil(math.log(2**29,2))
30.0

To avoid this problem, you could simply use round() instead of math.ceil.

(2,29) is just the first pair of many problematic ones:

[(2, 29), (2, 31), (2, 39), (2, 47), (2, 51), (2, 55), (2, 58), (2, 59), (2, 62), (2, 93), (4, 29), (4, 31), (4, 93), (5, 3), (5, 6), (5, 12), (5, 13), (5, 17), (5, 21), ...
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124