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

1 Answer

0 votes
by (35.8k points)

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.

...