Negative square root

Deadie picture Deadie · Aug 12, 2011 · Viewed 12.3k times · Source

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?

Answer

Alexandre C. picture Alexandre C. · Aug 12, 2011
#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)));