+5 votes
in Programming Languages by (40.5k points)
I want to find the nearest power of 2 for a given number. How can I do it in R?

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

You can use log2(), floor() and ceiling() functions to find the nearest power of 2 for a given number.

Here is an example:

x <- 50
lower <- 2^floor(log2(x))
upper <- 2^ceiling(log2(x))
if(x-lower < upper-x){
  ans <- lower
}else{
  ans <- upper
}
print(ans)

The above code will print 64.


...