Search code examples
c++definitionpow

C++: Inconsistent std::pow( type ) definition


I am using the std::pow(std::complex) defined in <cmath>, which returns nan. I expected the following for the complex power implementation:

#include <complex>
#include <cmath>
cout << std::pow(std::complex(0.0, 0.0), 0) // should return (1, 0), but returns (nan,nan)

cout << std::pow(0.0, 0) // e.g. returns 1.0 as expected!

Why is the std::pow(..., 0) chose differently for different number types? And what be the best way to use a uniquely defined power function for all types?


Solution

  • 00 is to be understood as a limit rather than an arithmetic expression you can evaluate directly.

    On the set of real numbers, this limit "exists" (simplifying here) and is 1, so that's the result you get.

    On the set of complex numbers on the other hand, you are approaching an essential singularity; there exists no single complex number you could assign to the limit 00. NaN is thus the only reasonable result.

    So if you need a consistent power function, treating 00 as NaN in the real case too would be the reasonable way to go, as setting 00 = 1 is somewhat dodgy in real arithmetic anyway; though less so than in the complex case.


    Note that I somewhat simplified the math here, but I'll repeat the key point to take away: no number exists that would be a meaningful result for 00 interpreted as the complex power function.
    This includes the number 1. For a mathematically more rigorous discussion, you might want to have a look at https://math.stackexchange.com/ or another more math-focused resource.

    Last, it is worth noting that the result of std::pow(std::complex(0.0, 0.0), 0) is implementation defined; the above is a justification for the reasonable choice your implementation made. However, from a strict C++-standard point of view and ignoring the math aspect of this problem, 1 would also be a compliant result, as would be pi, -∞ and 0.