Negative square root

爱⌒轻易说出口 提交于 2019-12-22 08:09:09

问题


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?


回答1:


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



回答2:


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.




回答3:


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




回答4:


Maybe something like this

double negativeNumber = -321;
std::complex<double> number( negativeNumber, 0 );
std::complex<double> result = sqrt( number );
double realpart = result.real();


来源:https://stackoverflow.com/questions/7042760/negative-square-root

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!