Finding complex roots using quadratic forumla!

Hello, please help me:i am failing to understand how i would go about getting the sqaure root of a complex number in c++

note this for the code below:

 
typedef complex<double> complex_d;


This is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void solve_for_x(int a, int b, int c)
{
//A true discriminant is positive! i.e no complex roots!
    if ( discriminant_sign(a,b,c) == true)
    {
        double x1 = (-b + sqrt(pow(b,2)-4*a*c))/2*a;
        double x2 = (-b - sqrt(pow(b,2)-4*a*c))/2*a;

        cout << "ans is: " << x1 << "\t&\t" << x2 << "\n";
    }

//A false discriminant is negative! i.e has complex roots!
    else if( discriminant_sign(a,b,c) != true )
    {
        int discriminant_i = abs(pow(b,2) - 4*a*c);
        complex_d discriminant {0, discriminant_i};
        complex_d x1 = (-b + sqrt(discriminant.imag()))/2*a;
        complex_d x2 = (-b - sqrt(discriminant.imag()))/2*a;

        cout << "ans is: " << x1.real() << "+" << x1.imag() << "\t&\t" << x2.real() << "+" << x2.imag() << "\n";
    }
}


I have no idea how to go about implementing this part:
1
2
        complex_d x1 = (-b + sqrt(discriminant.imag()))/2*a;
        complex_d x2 = (-b - sqrt(discriminant.imag()))/2*a;


since sqrt(discriminant.imag()) is not taking the square root of the complex number but return a double and not a complex type!

Thanks!
For a > 0:
(sqrt(a/2) + sqrt(a/2)i) ^ 2 = 0 + ai
(sqrt(a/2) - sqrt(a/2)i) ^ 2 = 0 + ai

Note: cos(pi/4) = 1/sqrt(2)
Thanks for the reply:

one other soultion i found is to use this:

1
2
3
4
5
6
7
8
9
10
11
12
13
    else if( discriminant_sign(a,b,c) != true )
    {
        int discriminant_i = abs(pow(b,2) - 4*a*c);

        pair <int, complex_d> x1;
        pair <int, complex_d> x2;

        x1 = make_pair(-b/2*a , sqrt(discriminant_i)/2*a);
        x2 = make_pair(-b/2*a , sqrt(discriminant_i)/2*a);

        cout << "ans is: " << x1.first << "+" << x1.second.real() << "j" << "\t&\t"
            << x1.first << "-" << x1.second.real() << "j" << "\n";
    }
Topic archived. No new replies allowed.