Pages - Menu

Sunday 14 October 2012

Solving a quadric ecuation in C

This function computes the two roots of a quadric ecuation.

In order to work easily with a complex number, I defined a structure consisting of two doubles, r being for the real part of a complex number and i for the imaginary part.
typedef struct
{
   double r;
   double i;
} double_c;

/*
 * Description:
 *  Finds the two roots of a quadric ecuation
 * Parameters:
 *  a   - the first coefficient of the ecuation
 *  b   - the second coefficient of the ecuation
 *  c   - the third coefficient of the ecuation
 *  root1 - the first root of the ecuation
 *  root2 - the second root of the ecuation
 */
void QuadricEcuation(double a, double b, double c, double_c *root1, double_c *root2)
{
    double discriminant = 0;
    discriminant = b*b-4*a*c;
    if ((discriminant == 0) && (a != 0)) //the roots are equal
    {
        (*root1).r = -b/2*a;
        (*root1).i = 0;
        (*root2).r = (*root1).r;
        (*root2).i = (*root1).i;
    }
    else if ((discriminant > 0) && (a != 0)) //the roots are real numbers
    {
        (*root1).r = (-b+sqrt(discriminant))/(2*a);
        (*root1).i = 0;
        (*root2).r= (-b-sqrt(discriminant))/(2*a);
        (*root2).i = 0;
    }
    else if (a != 0)//the roots are complex numbers
    {
        (*root1).r = -b/(2*a);
        (*root1).i = sqrt(-discriminant)/(2*a);
        (*root2).r = -b/(2*a);
        (*root2).i = -sqrt(-discriminant)/(2*a);
    }
}

Example:

#include<stdio.h>
#include<conio.h>
#include<math.h>

void QuadricEcuation(double a, double b, double c, double_c *root1, double_c *root2);

int main(void)
{
    double a = 0, b = 0, c = 0;
    double_c root1, root2;
    printf("Enter the three coefficients of the quadric ecuation:\n");
    scanf("%lf",&a);
    scanf("%lf",&b);
    scanf("%lf",&c);
    QuadricEcuation(a,b,c,&root1,&root2);
    printf("\t\tThe roots are:\n");
    printf("\t\t\t%.3f+%.3fi and %.3f+%.3fi",root1.r,root1.i,root2.r,root2.i);
    getch();
    return 0;
} 
Output:  

No comments:

Post a Comment