Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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|$.

share|improve this question
1  
Ceiling[Log[2, #]] & –  acl Jul 28 at 14:14
    
For integers there is IntegerLength[A, 2]. –  Daniel Lichtblau Jul 28 at 20:12

2 Answers 2

up vote 10 down vote accepted

How about this?

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

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

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

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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