Вопрос

I just found out that when entering a negative x and a decimal y, Math.Pow() returns the not-defined value as result, which is wrong I guess. Calculating this in other programs, even like the windows Calculator works with a correct result. Also this case is not mentioned in the documentation.

Target Framework is 4.

Can anyone explain this?

Это было полезно?

Решение

The result is going to be complex number, so you have to use Complex class from System.Numerics namespace.

Complex n = new Complex(-2, 0);
Complex result = Complex.Pow(n, 1.1);

In case if result is real number (integer power), then you can use Math.Pow.

As @JeppeStigNielsen mentioned, the conversion from int/double to Complex is implicit, so the code can be shortened to:

Complex result = Complex.Pow(-2, 1.1);

Другие советы

Also this case is not mentioned in the documentation

You sure? From it's documentation;

Parameters

x < 0 but not NegativeInfinity; y is not an integer, NegativeInfinity, or PositiveInfinity.

Return value

NaN

I'm not sure which OS you tried but it doesn't work in calc.exe (Win7 - 64bit) says Invalid Input.

As Ulugbek mentioned, taking 1.1 power of a negative value creates a complex number. Because (-2)1.1 = (-2)11/10 = (-2)1/1011 and getting 10 times rooth of -2 returns a complex number.

Since Math.Pow takes and returns double values, this doesn't fit with requirements. You can use Complex class from System.Numerics.

http://www.wolframalpha.com/input/?i=-2^1.1

enter image description here

Further reading: How is Math.Pow() implemented in .NET Framework?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top