Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Pow taking an integer value

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;
}
like image 926
Dave Mateer Avatar asked Jun 25 '12 20:06

Dave Mateer


1 Answers

In your special case, when you are calculating 2 to the power x, you can use a simple left shift. This would simplify your code to:

public static int TwoPowX(int power)
{
    return (1<<power);
}
like image 197
user5072377 Avatar answered Oct 10 '22 07:10

user5072377