Negative square root

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?

+4
source share
4 answers
#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))); 
+6
source

sqrt(-x) where x is a positive number, just 0 + sqrt(x)*i . The real part is 0.

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 .

+5
source

If what you call a negative number is real, then should the real part of its square root be 0 ?

+3
source

Maybe something like this

 double negativeNumber = -321; std::complex<double> number( negativeNumber, 0 ); std::complex<double> result = sqrt( number ); double realpart = result.real(); 
0
source

All Articles