Rounding to the nearest integer power of a given base

后端 未结 1 1436
逝去的感伤
逝去的感伤 2021-01-19 15:24

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

相关标签:
1条回答
  • 2021-01-19 15:51

    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)

    0 讨论(0)
提交回复
热议问题