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)
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
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