Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why (0+0i)^{0} == (nan, nan) in c++

take a look at the code blew:

#include <complex>
#include <iostream>

int main()
{
    std::cout << std::pow( std::complex<double>(0,0), std::complex<double>(0,0) ) << "\n";
    std::cout << std::pow( std::complex<double>(0,0), double(0) ) << "\n";

    return 0;
}

g++(4.8.1) gives an output of

(nan,nan)
(-nan,-nan)

while clang++(3.3) gives an out put of

(-nan,-nan)
(-nan,-nan)

But I am expecting (1.0, 0.0).

Can anyone give an explanation?

like image 310
Feng Wang Avatar asked Jun 28 '13 14:06

Feng Wang


People also ask

What is NaN error in C?

NaN, an acronym for Not a Number is an exception that usually occurs in the cases when an expression results in a number that is undefined or can't be represented. It is used for floating-point operations. For example: The square root of negative numbers.

What is the value of NaN in C?

NaN is unordered: it is not equal to, greater than, or less than anything, including itself. x == x is false if the value of x is NaN. You can use this to test whether a value is NaN or not, but the recommended way to test for NaN is with the isnan function (see Floating-Point Number Classification Functions).

What library is NaN in C++?

C++ nan() - C++ Standard Library.


2 Answers

According to std::pow documentation

Return value
base raised by power (exp or iexp).
Domain error occurs if base is 0 and exp is less than or equal to ​0​. NAN is returned in that case. [...]

In your code, you have both base with 0 and exp equal to 0 since the complex number 0 + 0 *i is still 0. So NaN seems expected.

By courtesy of @Fred Larson, and according to overloaded std::pow for std::complex

Computes complex x raised to a complex power y. The operation is defined as exp(y · log(x) ). A branch cut exists along the negative real axis. The result of pow(0, 0) is implementation-defined.

like image 175
taocp Avatar answered Nov 08 '22 03:11

taocp


As Fred Larson correctly points out the documentation says:

The result of pow(0, 0) is implementation-defined.

Mathematically this makes sense since we have a contradictory situation where N^0 should always be 1 but 0^N should always be 0 for N > 0, so you should have no expectations mathematically as to the result of this either. This Wolfram Alpha forum posts goes into a bit more details.

The case where the imaginary portion of the complex number is not zero is more complex situation. If the x in x^y is real then it should also be undefined but if x has an imaginary component then it looks like it is no longer undefined.

like image 35
Shafik Yaghmour Avatar answered Nov 08 '22 03:11

Shafik Yaghmour