Search code examples
pythonintlogarithm

Smallest integer value greater than or equal to value of log


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)

Solution

  • 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