Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate the closest power of 2 or 10 a number is?

Tags:

algorithm

math

What is the most efficient way to cacluate the closest power of a 2 or 10 to another number? e.g.

3.5 would return 4 for power of 2 and 1 for power of 10

123 would return 128 for power of 2 and 100 for power of 10

0.24 would return 0.25 for power of 2 and 0.1 for power of 10

I'm just looking for the algorithm and don't mind the language.

like image 824
Nick Randell Avatar asked Nov 05 '08 01:11

Nick Randell


People also ask

How do you find the nearest power of 2?

next = pow(2, ceil(log(x)/log(2))); This works by finding the number you'd have raise 2 by to get x (take the log of the number, and divide by the log of the desired base, see wikipedia for more). Then round that up with ceil to get the nearest whole number power. This is a more general purpose (i.e. slower!)

How do you find the nearest power of a number?

For the number N, find the nearest powers of K greater and smaller. The smaller power of K will be the floor value (say X) of logKN. So the value will be pow(K, X). [floor value of P = closest integer to P which is ≤ P]

What is the value of 2 Power 10?

∴ The value of 2 power 10 is 1024 .


1 Answers

n^round(log_n(x))

where log_n is the logarithm to base n. You may have to modify the round() depending on how you define "closest".

Note that log_n(x) can be implemented as:

log_n(x) = log(x) / log(n)

where log is a logarithm to any convenient base.

like image 82
Greg Hewgill Avatar answered Sep 28 '22 04:09

Greg Hewgill