Negative square root
Asked Answered
B

4

5

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?

Bravo answered 12/8, 2011 at 15:49 Comment(1)
so many problems for developers, physicists because of wrong axiomatics in multiplication...Kidderminster
R
7
#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)));
Roundshouldered answered 12/8, 2011 at 15:59 Comment(0)
N
6

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.

Nenitanenney answered 12/8, 2011 at 15:58 Comment(0)
E
4

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

Encroach answered 12/8, 2011 at 15:55 Comment(1)
+1; I was so excited to post this answer, but it was already here!Adelaidaadelaide
E
0

Maybe something like this

double negativeNumber = -321;
std::complex<double> number( negativeNumber, 0 );
std::complex<double> result = sqrt( number );
double realpart = result.real();
Embus answered 12/8, 2011 at 15:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.