Math.Pow取整数值

Dav*_*eer 9 c# floating-accuracy pow

来自http://msdn.microsoft.com/en-us/library/system.math.pow.aspx

int value = 2;
for (int power = 0; power <= 32; power++)
    Console.WriteLine("{0}^{1} = {2:N0}",
                      value, power, (long) Math.Pow(value, power));
Run Code Online (Sandbox Code Playgroud)

Math.Pow将双精度作为参数,但在这里我们传递的是int.

问题:如果隐式转换为双重发生,是否存在浮点舍入错误的危险?

如果是,最好使用以下内容:

public static int IntPow(int x, uint pow)
{
    int ret = 1;
    while (pow != 0)
    {
        if ((pow & 1) == 1)
            ret *= x;
        x *= x;
        pow >>= 1;
    }
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*igt 5

不,没有可能因转换而导致舍入错误double. double可以精确地表示属于幂函数域的所有整数.


小智 5

在您的特殊情况下,当您计算2的幂x时,您可以使用简单的左移.这会简化您的代码:

public static int TwoPowX(int power)
{
    return (1<<power);
}
Run Code Online (Sandbox Code Playgroud)


Ser*_*rvy 4

是的,存在向 double 的隐式转换,并且因此可能会出现浮点舍入错误。

至于是否值得使用您建议的替代方法,这取决于应用程序。浮点舍入误差是完全不可接受的吗?您会使用适合 int32 的数字(不需要太多的幂就会溢出)吗?

  • 将 int 转换为 double 时出现浮点舍入错误?请就此写更多内容。 (2认同)