How do you take the square root of a negative number in C ++?I know that it should return the real and difficult part, do I get NaN?How can I accept the real part?
#include <complex> int main() { std::complex<double> two_i = std::sqrt(std::complex<double>(-4)); }
or simply
std::complex<double> sqrt_minus_x(0, std::sqrt(std::abs(x)));
sqrt(-x) where x is a positive number, just 0 + sqrt(x)*i . The real part is 0.
sqrt(-x)
0 + sqrt(x)*i
In the general case, the real part x > 0 ? sqrt(x) : 0 x > 0 ? sqrt(x) : 0 , and the imaginary part x < 0 ? sqrt(x) : 0 x < 0 ? sqrt(x) : 0 .
x > 0 ? sqrt(x) : 0
x < 0 ? sqrt(x) : 0
If what you call a negative number is real, then should the real part of its square root be 0 ?
0
Maybe something like this
double negativeNumber = -321; std::complex<double> number( negativeNumber, 0 ); std::complex<double> result = sqrt( number ); double realpart = result.real();