Click here to Skip to main content
Click here to Skip to main content

Equation Solver in C

By , 1 Oct 2009
 

Introduction

This program can solve 4 types of equations.

Background

I'm a ninth grader from India. I was too bored to solve equations and check them all by myself. So I wrote this program.

Knowledge of the quadratic formula (including imaginary roots) and synthetic division will help a lot.

Using the Code

The method for solving linear equations in one variable is quite simple.

ax+b = 0 is the format for one variable equations. The variables a and b are determined and x is computed by -b/a.

The method I have implemented for solving linear equations in two variables is a formula which can be derived by operating on both sets of the equation. The formula for the equations is:

ax + by + c = 0  
dx + ey + f = 0  
x = (fb-ce)/(ae-db) 
y = (cd -fa)/(ae-db) 

To solve quadratic equations, we use the quadratic formula:

Root 1 = (-b + Sqrt(b2 - 4ac))/2a  
Root 2 = (-b - Sqrt(b2 - 4ac))/2a   

b2-4ac is called the "Discriminant" which is generally denoted by D.

If D >= 0, we will get Real roots.

Things get complicated when we get imaginary roots.

If D<0, then we get imaginary roots and the roots will change as follows:

Root 1 = (-b + Sqrt(4ac - b<sup>2</sup>)i)/2a   
Root 2 = (-b + Sqrt(4ac - b2)i)/2a

C does not support complex numbers. So, I decided to print the root as a string:

 printf("\nRoot 1 : %f+%fi",((-b)/(2*a)),disc);  

The first %f in the roots is -b/2a which is the real part of the root and the second %f prints 4ac-b2 with 'i' representing the imaginary part.

I don't know a method to solve all sorts of cubic equations. If anyone gets to know of a method, please inform me of the method in a language a ninth grader like me can understand.

float a,b,c,d,x1,x2,x3,disc;
int i;
float expr;
clrscr();
printf("ax^3 + bx^2 + cx + d = 0\n Enter a,b,c,d : \n");
scanf("%f,%f,%f,%f",&a,&b,&c,&d);
i = 0;
while(i<abs(d))
{
expr = a*pow(i,3)+b*pow(i,2)+c*i+d;
if(expr==0)
{
x1=i;
break;
}
expr = a*pow(-i,3)+b*pow(-i,2)+c*(-i)+d;
if(expr==0)
{
x1=-i;
break;
}
i++;
}
printf("Root 1 = %f",x1);
b = b + (a*(x1));
c = c + (b*(x1));
disc = (b*b)-(4*a*c);
if(disc>=0)
{
x2 = (-b+sqrt(disc))/(2*a);
x3 = (-b-sqrt(disc))/(2*a);
printf("\nRoot 2 = %f\nRoot 3 = %f",x2,x3);
}
else
{
disc = ((4*a*c)-pow(b,2))/(2*a);
printf("\nRoot 2 : %f+%fi",((-b)/(2*a)),disc);
printf("\nRoot 3 : %f-%fi",((-b)/(2*a)),disc);
}	

One root is found by trial and error method. If this fails, we cannot find any other root of the expression in this program. This is the method which I have implemented in the program. All the numbers (both positive and negative) till d are checked by substitution. If it succeeds, then the program moves to the next step.

b = b + (a*(x1));
c = c + (b*(x1));  

This is the place where synthetic division comes into play.

Synthetic division is a shortcut method for dividing a polynomial by a linear polynomial instead of using the long division method.

I will explain the process with an example.

Let the polynomial be (x3 + 2x2 - 4x + 8) and the linear polynomial (x + 2).

We have to divide them.

  1. Reverse the sign of the constant in the divisor. In this case, we have to make 2 into -2.
  2. Then write the co-efficients a, b, c and d in order. It will look like this: -2|1 2 -4 8
  3. Bring down the first co-efficient and multiply it by the divisor. Then add this to the second co-efficient. 2+(-2*1) = 0. The general form is bnew = b+(divisor * a).
  4. Then multiply the divisor again by the obtained result and add with the next co-efficient. -4+(-2*0) = -4. The general form is cnew= c+(divisor * bnew).
  5. Again multiply the divisor by the result obtained and add this to the next (last in this case) co-efficient. 8+ (-2*-4) =16.

In this example, we get the remainder as 16. If the polynomial is divided by one of its roots, we will get zero as the remainder in the last step. Then, the polynomial will be reduced to a quadratic equation of the form Ax2+Bx+C=0 where A is a, B is bnew and C is cnew.

Then the quadratic equation is solved.

Now, we have all 3 roots of the equation.

Any suggestions or improvements are welcome. Please inform me if there is another fool-proof method for solving 3rd degree equations. Methods suggested for solving 4th degree and higher degree equations are welcome with open hands.

History

  • 1st October, 2009: Initial post

Contact

You can either post a comment or mail me at r.anshul@gmail.com.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Anshul R
Student
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionoh himemberNoPoinT ba DA10 Feb '13 - 0:36 
can't find the right graphics.h can you help me with that?
AnswerRe: oh himemberpranav9510 Feb '13 - 0:59 
Delete the line with graphics.h and remove the line clrscr();
 
At that time, I was not aware of graphics.h being deprecated.
GeneralCubic EquationsmemberMichael Waters7 Oct '09 - 9:16 
Assuming you are deep enough into algebra to have learned about imaginary numbers (i.e. sqrt(-1), as opposed to real numbers) ...
 
Cubic equations DO have a closed form solution - a google (or wikipedia) search will lead you to the right algorithims. In brief, a cubic equation can either have ONE real root and TWO imaginary roots, or it can have THREE real roots. In the first case, the solution is actually rather simple, as the cubic can be decomposed into a pair of equations, one linear and the other quadratic. In the latter, it's a bit of a mess of algebra, and you have to decide which of the 3 roots you want in the end.
 
There are also certain categories of polynomials of various higher orders which have closed form solutions, but IIRC the cubic equation is the highest order general equation that can be solved in closed form. The rest you have to solve numerically (bisection, Newton, brent, etc.).
GeneralRe: Cubic Equationsmemberpranav957 Oct '09 - 15:10 
Sir, how do I decompose a cubic equation?
 
Please explain to me so that I can improve my article
GeneralRe: Cubic EquationsmemberMichael Waters8 Oct '09 - 4:34 
A good place to check for reference is
 
http://en.wikipedia.org/wiki/Cubic_function
 
The algebra is literally too long to post here. But the general description of the method is to first calculate the discriminant of the general cubic equation
 
ax^3 + bx^2 + cx + d = 0
 
as
 
18abcd - 4b^3d + b^2c^2 - 4ac^3 - 27a^2d^2
 
If the descriminant is < 0, then the equation has one real and two imaginary roots. If the descriminant is >= 0, it has three real roots. If the descriminant is == 0, then at least two and possibly all three of the roots are equal (for instance, that is the case for x^3 = 0).
 
Then, depending on whether you are looking at three real roots, or one real and two imaginary roots, you can choose whichever flavor of the various algebraic methods described in wikipedia most appeals to you.
 
One word of warning - the standard math librarires that are part of C++ don't handle roots or powers of negative numbers very well. Be VERY explicit when taking the cube root of a neagative number, or the cube of a negative number, so that the math functions don't crash and that they return the correct sign. YOU may know that the cube root of -27 is -3, but don't be surprised if the math library function returns 3, or crashes with a NaN error, instead.
GeneralRe: Cubic Equationsmemberpranav958 Oct '09 - 4:37 
Thank you.
 
I will try the code once my long exams end Cry | :((
 
It ends on November 5th
 
So please bear with me till that
GeneralProblem with Quadatic AnswersmemberMicroImaging5 Oct '09 - 10:48 
From my college numerical Analysis classes you have to watch for floating pointing rounding, and the prime example is the use of the quadratic equation roots as you have stated them. In order to reduce round off errors as much as possible.
You should only use the -b +/- sqrt()/2a which has the same sign, so you only add NEVER subtract.
The other root is then found by taking ratios. This is only good practice, and should be used to reduce numerical round off error in any calculation that you perform. Subtracting like large numbers and receiving a much smaller number as an answer is an invitation to disaster.
GeneralRe: Problem with Quadatic Answersmemberpranav956 Oct '09 - 2:21 
Thank you sir.
 
I have never heard of this method but this works great.
 
I will update my code and post it once my exams are over
GeneralNice Articlememberstoni2 Oct '09 - 3:48 
That's the way I started to use computers 30 jears ago. Big Grin | :-D
 
In order to solve a polinomial equatation of n-th degreee (cubical is 3rd) "Newtons Method" will do the job. It's an approximate method.
Google for it - there are many good descriptions/and pseudocode examples on the net - an code it.
 
I remember having fun coding it using pascal in the late 1980s for num mat lesson at university, but unfortunately I do not have the code anymore.
Also interesting is the "Gaussian elimination" to solve a linear equitation system (n equitations, n variables) . It's fun as well. Smile | :)
GeneralRe: Nice Articlememberpranav952 Oct '09 - 19:34 
Thank you
 
I will read about it and will try to improve my code after my exams get over
GeneralGood Job!memberkopota1 Oct '09 - 19:51 
If you can do this at 9, I'm sure you'll put a lot of us out of work by the time you complete your first degree OMG | :OMG: OMG | :OMG: . Keep coding Big Grin | :-D Big Grin | :-D .
GeneralGood jobmemberMarius Iulian Mihailescu1 Oct '09 - 19:08 
Your program it's very good, if you want to resolve all kinds of cubic equations you have to study more about equations and cubic function. Maybe this article will help you http://en.wikipedia.org/wiki/Cubic_function[^]. The first step is to understand how a cubic function it's working and after that try to make an alghoritm that takes in consideration all the cases. And don't forget about Lagrange but I don't know if you study in nine grade this.
 
Cheers
 
Marius Iulian Mihailescu
Software Developer, Internet Security

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 1 Oct 2009
Article Copyright 2009 by Anshul R
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid