In mathematics, a quadratic equation is a polynomial equation of the second degree. The general form is
where x represents a variable, and a, b, and c, constants, with a ≠ 0. (If a = 0, the equation becomes a linear equation.)
The constants a, b, and c, are called respectively, the quadratic
coefficient, the linear coefficient and the constant term or free term.
The term "quadratic" comes from quadratus, which is the Latin word for
"square". Quadratic equations can be solved by factoring, completing the
square, graphing, Newton's method, and using the quadratic formula.
The roots are given by the quadratic formula:
Output of this tutorial will be display as the following:
Source Code in JavaScript of Quadratic Equation:
document.write("<h1>Quadratic Equation</h1>"); //Display the title
do
{
var a = prompt("Enter cofficient a (a not equal to 0):");
}while(a==0) //User will be allow to continue when key in value for a coefficient that is non-zero in quadratic equation
do
{
var b = prompt("Enter cofficient b :"); //User provide b coefficient in quadratic equation
var c = prompt("Enter cofficient c :"); //User provide c coefficient in quadratic equation
}while(Math.pow(b,2)<(4*a*c)) //b^2 - 4ac must greater and equal than zero as we cant square root a negative number.
var eq=""; //set the equation to null string
if(Math.abs(a)==1) //Check if a coefficient is equal to one
eq = (a<0?"-":"")+"x<sup>2</sup>"; //Display X^2 or -X^2 depend on sign in front of one for a coefficient
else
eq = a+"x<sup>2</sup>"; //Display aX^2 where a coefficient rather than 1 or -1
if(b!=0) //Check b is not null
{
if(Math.abs(b)==1)
eq+=(b<0?"-":"+")+"x"; //Display X or -X depend on sign in front of one for b coefficient
else
eq+=(b>0?"+"+b:b)+"x"; //Display bX where b coefficient rather than 1 or -1
}
if(c!=0)
eq+=(c>0?"+"+c:c); //Display + or - depend or c coefficient
var x1 = ((-1*b)+Math.sqrt(Math.pow(b,2)-(4*a*c)))/(2*a); //Calculate X1
var x2 = ((-1*b)-Math.sqrt(Math.pow(b,2)-(4*a*c)))/(2*a); //Calculate X2
document.write("<h2>Expression : </h2>");
document.write("<p style='text-indent:15px; font-size:14pt'>"+eq+"</p>"); // Display the final equation
document.write("<b><i>where,</i></b><br />");
document.write("<i>a="+a+"; b="+b+"; c="+c+"</i>"); //Show the a, b and c coefficient
document.write("<h2>Solution to X : </h2>");
document.write("<p style='text-indent:15px; font-size:14pt'>x<sub>1</sub>="+x1.toFixed(2)+"</p>"); //Display X1 value
document.write("<p style='text-indent:15px; font-size:14pt'>x<sub>2</sub>="+x2.toFixed(2)+"</p>");
//Display X2 value
</script>
It is working. I have put a constrain on coefficient a, b and c to fulfill the condition of b^2 - 4ac >= 0.
ReplyDeleteThe quadratic with b^2 - 4ac = 0 will obtain same values in both x1 and x2 as there will be only one point intersection on the x-axis.