2

I am trying to compute the nearest 2^n to a very large number(<=10^19)

I have tried to use math.log(number,2). But that is giving wrong results for very big numbers. How should I do this without using other libraries?

a = 9843649374639837463  # a is any num between 1 and 10^9
number = int(math.log(a,2))
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485

1 Answers1

7

The large integer input is being converted to a float with limited precision, so some input precision is being lost. Also, math.log2() can be more accurate than math.log() because it is fine-tuned for base two.

There is an int method that will be dead-on accurate, bit_length():

>>> a = 9843649374639837463
>>> a.bit_length()
64
>>> bin(a)
'0b1000100010011011101010101111001111001100111001110101000100010111'

Note, the floating point log is pretty close but not exact:

>>> a = 9843649374639837463
>>> 2.0 ** math.log2(a)
9.843649374639845e+18
>>> abs(a - 2.0 ** math.log2(a))
8192.0
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485