Math.Pow taking an integer value

Dave Mateer picture Dave Mateer · Jun 25, 2012 · Viewed 14k times · Source

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

Math.Pow takes doubles as arguments, yet here we are passing in ints.

Question: Is there any danger of floating point rounding errors if there is an implicit conversion to double happening?

If yes, it is better to use something like:

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;
}

Answer

Ben Voigt picture Ben Voigt · Jun 25, 2012

No, there's no possibility of rounding error caused by the conversion to double. double can exactly represent all integers which fall in the domain of the power function.