-1

math.log2 and math.log are giving me wrong results for some high numbers, tested it via online py interpreter and on a local machine.

>>>print(2**72)  

>>>4722366482869645213696 #Correct

>>>math.log2(4722366482869645213697)

>>>72.0 #Wrong

>>>math.log(4722366482869645213697,2)

>>>72.0 #Wrong

>>>math.log2(39614081257132168796771975174)

>>>95.0 #Wrong

>>>print(2**95)

>>>39614081257132168796771975168 #Correct

Am I missing something or its some bug?

Alec
  • 8,529
  • 8
  • 37
  • 63
  • 1
    Why is 72.0 "wrong"? What float would you like instead? – wim Apr 24 '19 at 19:44
  • Hey.72.0 Suggests that its the same as 2**72 and its not, it should return something like 71.xxxxxxxxx. – Ragnar Lothbrok Apr 24 '19 at 19:48
  • 1
    Your question is about checking if an integer is a power of two. Next time you ask, include the context of your question and which problem you are trying to solve. Meanwhile, see my answer. – Olivier Melançon Apr 24 '19 at 20:32

2 Answers2

0

You are missing that math.log is giving you IEEE floating point with a maximum of 52 bits of precision.

Your answers are correct to within the limits of the representation.

btilly
  • 43,296
  • 3
  • 59
  • 88
0

The actual answer is about 72.0000000000000000000003.

The absolute error being smaller than the floating point error in that range, you got the closest floating point approximation of log2(72) a computer can store with a 64 bits float.

If you want to check whether an integer is an exact power of two, then you can check whether only it's left-most bit is a 1.

if 1 << (x.bit_length() - 1) == x:
    print("x is a power of 2")
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73