Take the 2-minute tour ×

How do you take the square root of a negative number in c++? I know it should return a real and a complex part, I get a nan? How do I take the real part?

share|improve this question
sqrt(abs(numvar))? –  Marc B Aug 12 '11 at 15:51
add comment

4 Answers

up vote 2 down vote accepted
#include <complex>

int main()
    std::complex<double> two_i = std::sqrt(std::complex<double>(-4));

or just

std::complex<double> sqrt_minus_x(0, std::sqrt(std::abs(x)));
share|improve this answer
add comment

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

share|improve this answer
+1; I was so excited to post this answer, but it was already here! –  Chris Cunningham Aug 12 '11 at 18:50
add comment

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

In general, the real part is x > 0 ? sqrt(x) : 0 and the imaginary part is x < 0 ? sqrt(x) : 0.

share|improve this answer
add comment

Maybe something like this

double negativeNumber = -321;
std::complex<double> number( negativeNumber, 0 );
std::complex<double> result = sqrt( number );
double realpart = result.real();
share|improve this answer
add comment

Your Answer


