Instead, this operation returns -1.IND, since sqrt(-1)
returns -1.IND. Does the domain error mentioned on the C++ reference that this sqrt returns for negative values not retain the info that this is actually i?
Is there some way to perform this operation for all negative numbers, so that it returns the correct value, i.e. pow(sqrt(-36), 2)
will return -36?
You can use std::complex to achieve your goal, like this:
#include <complex>
#include <iostream>
int main() {
const std::complex<double> result =
std::pow(std::sqrt(std::complex<double>(-36,0)), 2);
std::cout << result << std::endl;
std::cout << "Real part = " << result.real() << std::endl;
}
Output:
(-36,0)
Real part = -36
Note that std::sqrt(std::complex) is used here.
The reason behind the behaviour you encountered is the signatures of sqrt, namely:
double sqrt (double x);
float sqrt (float x);
long double sqrt (long double x);
double sqrt (T x); // additional overloads for integral types
which means that no matter which prototype will be used, you are getting nothing better than a nan
(or a +-inf), since the return types can not support the imaginary part. That's why std::complex
exists.
So, sqrt(-1)
will be replaced by a nan
probably, which can not be treated by pow()
, so that -1 remains intact, because of the exponent. As a result the information is already lost after the call to sqrt()
and pow()
can do nothing about it.