0

I have some integer count suppose '51' and I want represent that much of integers in binary number. Here I need to do log(51) so i get some float value as 3.93182563272. But I want it in some integer format as 4 which could be used to represent 51 integers. Log value can be calculated as

import math
math.log(51)
DummyGuy
  • 425
  • 1
  • 8
  • 20
  • You mean you want to round up the float to the nearest integer? – Martijn Pieters May 09 '14 at 11:47
  • 1
    Logarithm in which base? Since you mention binary numbers, I suspect base 2 log. In that case, be aware that `math.log` doesn't do that, it uses base e (natural logarithm). –  May 09 '14 at 11:48

2 Answers2

2

If you want the number of binary digits, that would be base 2, whereas math.log by default returns the natural logarithm (base e). A second argument can be used to specify an alternative base. Then you can use math.ceil to round up the number.

math.ceil(math.log(51, 2))
6.0

You haven't specified a python version but if you have python 3, (thanks @delnan), you can use math.log2 instead, which should be more accurate:

math.ceil(math.log2(51))
6.0

numpy also has a log2 method (but is probably overkill for this application).

math.ceil actually returns a float, so if you want an integer you can wrap the expression in int:

int(math.ceil(math.log(51, 2)))
6

By the way, there is also the function bin which you might want to look at. It returns a string containing the binary representation of an integer:

bin(51)
'0b110011'

...but if you don't want to mess around with any of that (thanks again @delnan), you can just use bit_length instead:

(51).bit_length()    
6
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • 1
    FYI `math.log(x, 2)` is less accurate than `math.log2(x)`, and `int(ceil(log2(x))` is in many ways worse than `x.bit_length()` if `x` is an integer. –  May 09 '14 at 12:07
  • @delnan I don't have math.log2 (python 2.7.3). I notice that numpy has a log2 method, is that what you mean? – Tom Fenech May 09 '14 at 12:11
  • No, I assumed Python 3's `math` and `int`. I rarely work with 2.x these days so I sometimes forget what's backported and what's not. –  May 09 '14 at 12:15
  • @delnan thanks for your contributions, I've edited so that hopefully all of it has been included. – Tom Fenech May 09 '14 at 12:28
  • @TomFenech thank you. I am using python 2.7. – DummyGuy May 09 '14 at 18:08
0

You could use the ceiling "round up" function before you cast it to an int:

math.ceil(math.log(51)) # round up

You should also have a look at:

math.floor() # round down
math.round()

If you need to save it as a integer type you can cast it to that type:

int()
cchristelis
  • 1,985
  • 1
  • 13
  • 17