Calculate power of a negative number

后端 未结 3 707
清酒与你
清酒与你 2021-01-23 03:23

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 do

3条回答
  •  走了就别回头了
    2021-01-23 03:51

    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.

提交回复
热议问题