Search code examples
c++mathsqrt

Negative square root


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?


Solution

  • #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)));