Rounding to the nearest integer power of a given base
I'm trying to round a number to the next smallest power of another number. I'm not particular on which direction it rounds, but I prefer downwards if possible.
The number x
that I'm rounding will satisfy: x > 0
, and usually fits within the range 0 < x <= 1
. Only rarely will it be above 1.
More generally, my problem is: Given a number x
, how can I round it to the nearest integer power of some base b
?
I wo开发者_StackOverflow社区uld like to be able to round towards arbitrary bases, but the ones I'm most concerned with at the moment is base 2 and fractional powers of 2 like 2^(1/2), 2^(1/4), and so forth. Here's my current algorithm for base 2.
double roundBaseTwo(double x)
{
return 1.0 / (1 << (int)((log(x) * invlog2))
}
Any help would be appreciated!
You've got the right idea; for any base x, x ^ floor( log_x(n) )
is what you want. (Where log_x
represents 'log to the base x')
In C#:
static double roundBaseX(double num, double x)
{
return Math.Pow(x, Math.Floor(Math.Log(num, x)));
}
If you can't take logarithms to an arbitrary base, just use the formula: log_x(n) = log(n) / log(x)
精彩评论