Question

The 'e' language has a 'ilog2' function but I need a 'ceiling of log2' type function - what's the best way to do this?

I could invoke a Perl through the system command and use POSIX::ceil...

Was it helpful?

Solution

Invoking perl script might be computational expensive. Instead add 0.5 to log2 and typecast (not sure if e-language supports it) to integer.

Another try:

  Let y = ilog2(x);
  if ((x & x-1) == 0)  //Check if x is power of 2 
      return y; 
  else 
      return y+1;

OTHER TIPS

I would have done something like this:

ceil_log2(in : uint): uint is {  
    var bottom := ilog2(in);  
    result = (in == ipow(2,bottom)) ? bottom : bottom + 1;  
};

If you don't mind doing it in real:

ceil_log2(in: uint): uint is {
  result = ceil(log10(in)/log10(2)).as_a(uint);
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top