5
$\begingroup$

I am looking for something like nextpow2 in MATLAB like this:

P = nextpow2(A) returns the exponents for the smallest powers of two that satisfy $2^P\geq\left|A\right|$.

$\endgroup$
2
  • 1
    $\begingroup$ Ceiling[Log[2, #]] & $\endgroup$
    – acl
    Jul 28, 2014 at 14:14
  • 1
    $\begingroup$ For integers there is IntegerLength[A, 2]. $\endgroup$ Jul 28, 2014 at 20:12

3 Answers 3

12
$\begingroup$

How about this?

nextpow2[a_] := Ceiling @ Log[2, Abs @ a];

or

nextpow2[a_] := Ceiling[RealExponent[a, 2]]

The same thing in a different style:

f1 = Ceiling @* Log2 @* Abs;  (* v10 syntax *)

Or:

f2 = ⌈Log2 @ Abs @ #⌉ &;

A plot:

Plot[f2[x], {x, -10, 10}, Filling -> 0]

enter image description here

$\endgroup$
7
  • 1
    $\begingroup$ @Mr.Wizard, Thank you! I learned something from you. $\endgroup$ Jul 28, 2014 at 14:30
  • $\begingroup$ @Mr.Wizard Do you know if the v10 syntax is documented anywhere? Searching for @* in the documentation turns up nothing. $\endgroup$
    – user484
    Jul 28, 2014 at 18:00
  • 2
    $\begingroup$ @Rahul Yes, it is: Composition. See also RightComposition. (I suppose the search failed because both @ and * are simple wildcards.) $\endgroup$
    – Mr.Wizard
    Jul 28, 2014 at 18:03
  • $\begingroup$ Re "v10 syntax": is it just the shortcut notation @* that was added in Mathematica 10*? Note that Composition dates to version 2.0. $\endgroup$
    – murray
    Jul 28, 2014 at 18:43
  • $\begingroup$ @murray. Yes, it's just the infix notation that was added in V10 $\endgroup$
    – RunnyKine
    Jul 28, 2014 at 19:51
6
$\begingroup$

You have a good answer already, but I'll mention the following since it may be useful in the future.

Many built-in functions are written in MATLAB and can be viewed, in this case edit nextpow2.m brings up the source for this function, which can be used as a starting point to implement in Mathematica.

$\endgroup$
2
$\begingroup$

Not exactly the same, but very closely related is BitLength.

BitLength[n] gives the number of binary bits necessary to represent the integer n.

For positive n, BitLength[n] is effectively an efficient version of Floor[Log[2,n]]+1.

For negative n, it is equivalent to BitLength[BitNot[n]]

When is it not equivalent to nextpow2?

  • It works for integers only.

  • When the argument is positive and an integer power of 2, the result of BitLength will be one greater than that of nextpow2.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.