I am trying to round a number to the next lowest power of another number. I donβt know in which direction it is spinning, but I prefer down if possible.
The number x that I am rounding will satisfy: x > 0 and usually fits the range 0 < x <= 1 . Less commonly, it will be above 1.
In general, my problem: Given the number x , how can I round it to the nearest integer power of some base b ?
I would like to be able to round to arbitrary bases, but at present I am most interested in base 2 and fractional powers of 2, such as 2 ^ (1/2), 2 ^ (1/4), and so on. Here is my current algorithm for base 2.
double roundBaseTwo(double x) { return 1.0 / (1 << (int)((log(x) * invlog2)) }
Any help would be appreciated!
source share