Vedanshu
Vedanshu

Reputation: 627

Calculate power of a negative number

I relatively new to C# and since Math.Pow(x,y) returns NaN for a negative number(read: not negative power), I want to know how to calculate result more efficiently. What I am doing write now is a basic for loop, but I want to know if it can be implemented in shorter way (using Linq maybe)?

for(int i=0;i<power;i++)
       {
           result = result * num;
       }

Upvotes: 2

Views: 6271

Answers (3)

PedPak
PedPak

Reputation: 177

in Pow(double base, double power), when base < 0 and power is fractional ( ex: power=0.5) , then NaN will be generated, because it is calculable in complex domain not in real domain. so may be you need to check the base and power of pow function before using them. in this case you should return your desired value as undefined value (instead of NaN).

the bellow function performs this operation, and returns 0 instead of NaN:

// pow with desired Nan
public double Pow(double x,double y){
    double MyNaN = 0; // or any desired value for Nan
    double result = MyNaN; 

    if (Math.Floor (y) != y) { // if y is fractional number
        if (x < 0)  // if x is negative number
            return result;
    }

    result = Math.Pow (x, y);
    return result;

}

Upvotes: 1

Eric Lippert
Eric Lippert

Reputation: 660024

Math.Pow(x,y) returns NaN for a negative number.

That's because arbitrary exponentiation is not defined for a negative base:

http://en.wikipedia.org/wiki/Exponentiation

when the base b is a positive real number, b to the n can be defined for all real and even complex exponents n via the exponential function

Now, exponentiation of negative numbers to get a real result is defined if the power is an integer, as in your case, but Pow will not calculate it for you. What you should do is:

  • Suppose you want to know Pow(-2, 5)
  • Give Pow the problem Pow(2, 5) instead.
  • Look at the exponent; if it is an even number then you've got the right answer. If it is an odd number, then make the answer negative.

So in this case, Pow(2, 5) returns 32. The exponent 5 is odd, so make it -32, and you're done.

Upvotes: 6

Related Questions