Question

I am just beginning C programming (not C++) and I have to convert the quadratic formula for adressing complex roots, and for printing these. The normal quadratic equation is as follows (for discriminant > 0):

else {
        /*  */
        x1 = ((-b) + sqrt(discr)) / (2 * a);
        x2 = ((-b) - sqrt(discr)) / (2 * a);
        printf("%s%.4lf%s%.4lf\n\n", "x1: ", x1, "\tx2: ", x2);
    }

When I try to convert this into its complex values I have used the following strategies:

  • Creating a new version of the result of the sqrt(discr), the complex part in the equation, by creating a variable _Complex double discr_complex = discr * I. -> OR discr_complex = discr + discr * I.

  • Making x1 and x2 complex by 'complex x1' or '_Complex c1' or 'complex x1 = ..formula.. * I' or '_Complex x1 = ...formula * I'.

  • Making every part complex by using the keyword complex.

For all these versions it does not print the correct complex output (#+#i). I tried printing the normal values, which works, but not for the complex part. I tried using the methods creal(x1) and cimag(x1) which do not work (undeclared reference to creal / cimag), or x1.real() / x1.imag(), which also doesn't work ('imag' in something not a structure or union).

Does anybody maybe know how to convert my x1 and x2 values into complex numbers, with maybe a clear explanation how to return each seperate part of the complex equation (real/imaginary) and how this conversion takes place taken my 'normal' formula?

Was it helpful?

Solution

The reason that calling creal does not work is that either you have not included the proper header complex.h or you are calling it with an argument x1 that is not of the correct type double complex. The second error, when you call x1.real() is because the . notation tries to access a member of a struct but x1 is a double.

I suggest using complex.h that enables working with complex numbers and define a new abc-formula that deals with complex numbers. Also note that you can not use 'regular' math functions like sqrt on variables of complex type but need to use the complex.h analogs e.g. csqrt()

#include <complex.h>

int main(void)
{
    double complex z = 1.0 + 0.5 * I;

    printf("The real part of z = %f\n", creal(z));
    printf("The iamginary part of z = %f\n", cimag(z));

    return 0;
}

Edit:

completely redefine your function, try something like this:

void complex_abc() {

    double complex a = 1;
    double complex b = 2;
    double complex c = 3;
    double complex x1;
    double complex x2;
    double complex d;

    d = b*b - 4 * a * c;
    x1 = ( -b + csqrt(d) ) / 2*a;
    x2 = ( -b - csqrt(d) ) / 2*a;

    printf("x1 = %f + i %f\n", creal(x1), cimag(x1));
    printf("x2 = %f + i %f\n", creal(x2), cimag(x2));

    return;
}

And as correctly noted by @Lutzl in the comments you need to link the math library with the flag -lm during compiling

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top