Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative square root

Tags:

c++

math

sqrt

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?

like image 826
Deadie Avatar asked Aug 12 '11 15:08

Deadie


2 Answers

#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)));
like image 131
Alexandre C. Avatar answered Oct 26 '22 11:10

Alexandre C.


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.

like image 23
tskuzzy Avatar answered Oct 26 '22 11:10

tskuzzy