How do I get the closes power of 2 from a number?

So I need to get the nearest power2 like (2, 4, 8, 16, 32) etc.
What I mean by that is for example:

function getClosestPow2(n)
	--return some wizard math IDK	
end

local floatNumber = 15.0
local powerOf2Number = getClosestPow2(floatNumber)

print(powerOf2Number)

Output:

16 --as it is the closest power of 2 to 15.0
return math.floor(x/2)*2 -- returns closest multiplication

does closest multiplication and closest exponent mean the same thing? no.

Not to sound rude, but this isn’t really what I asked about as it just returns the number n - 1 :derp:

Use the log function base 2. This question is vague because I’m not sure if you are wanting the closest power of 2 or the closest power of 2 that doesn’t exceed the result. I am going to assume the former. If you want the latter, simply get rid of the extra addition.

function closestpow(n)
  return math.floor(math.log(n, 2) + 0.5)
end

print(closestpow(56)) 
-- 6 (2^6 is 64)

EDIT: I misunderstood your question, but this function can be used to get what you want. Just raise 2 to the power of the output of closestpow:

function closestpow(n)
  return math.floor(math.log(n, 2) + 0.5)
end

print(math.pow(2, closestpow(15)))
-- 16
2 Likes

thank you soo much :smiley:
I would never have figured something like this out on my own!

1 Like

If you want a reason as to why, it’s because the logarithm base 2 of a number returns what you would need to raise 2 by to get that number.

For example, log2(9) is roughly 3.17, which means 2^3.17 is roughly 9. Simply put, if you take the logarithm base 2 of your input and round it to get n, you can also find the closest integer value of 2^n, which is what the above function does.

In fact, you can generalize your solution to any base by adding an additional parameter to the function:

function closestpow(n, b)
  return math.pow(b, (math.floor(math.log(n, b) + 0.5)))
end

print(closestpow(166, 3))
-- Closest power of 3 to 166
-- 243

print(closestpow(987, 10))
-- Closest power of 10 to 987
-- 1000
1 Like

I wanted to show you overall math how to do multiplication, you could use it

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.