Round to the nearest integer power of a given base

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!

+4
source share
1 answer

You have the right idea; for any x base, x ^ floor( log_x(n) ) is what you want. (Where log_x represents "log to base x")
In C #:

 static double roundBaseX(double num, double x) { return Math.Pow(x, Math.Floor(Math.Log(num, x))); } 

If you cannot take the logarithms to an arbitrary base, just use the formula: log_x(n) = log(n) / log(x)

+6
source

Source: https://habr.com/ru/post/1307887/


All Articles