SQRT delivers only one result

Pages: 123
> he square root of -4 is (0 + 2i)! Why sqrt() does not return that?

To get the square root of a complex number with std::sqrt(), #include <complex>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <complex>

int main()
{
    using cmplx = std::complex<double> ;

    for( double d : { 0, +4, -4 } )
    {
        std::cout << "std::sqrt(" << d << ") == " ;
        if( d < 0 ) std::cout << "0+" << std::sqrt( cmplx(d) ).imag() << "i\n" ;
        else std::cout << std::sqrt(d) << '\n' ;
    }
}

std::sqrt(0) == 0
std::sqrt(4) == 2
std::sqrt(-4) == 0+2i

http://coliru.stacked-crooked.com/a/b64ad5060d2a23ab
closed account (48T7M4Gy)
It really doesn't matter what the macro values of MATH_PI etc are, neither ∏ nor √2 have an exact value, they are both irrational numbers.

There will always be a difference because they can only be approximated. They are only exact as algebraic constants.
closed account (48T7M4Gy)
1
2
3
#include <iostream>
#include <complex> // <-- good work C++, I'd forgotten
etc


So there we go, apply the sqrt() function and we get a result, and the result is as totally expected, not another function. Tada ...

(I'll have to check, but it still looks as though it produces only the principal root, keeping in mind complex roots don't surrender to that name convention very well at all because the concept of +ve and -ve is somewhat lost with them)
Folks, listen to helios, he's right :)

One small note: the principal square root is actually one-to one (but not onto). It is defined for all complex numbers, but is discontinuous at all negative numbers and zero.
Try this on your calculator:

sqrt(−4−0.001×i)
output:
0.00025+2.000000016i

now try this:

sqrt(−4+0.001×i)

output:
0.00025−2.000000016i

As you can see, for small differences of the argument (the two inputs differ by 0.002i) you get a big difference in the output (the two output differ by almost 4i).

Last edited on
Topic archived. No new replies allowed.
Pages: 123