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