Quadratic equation in ECMAScript
Example for versions
SpiderMonkey 1.7
The example is meant to be executed from the web-browser. To run the example, copy the code to a file quadratic.js
and create an HTML file placed in the same directory and containing the following text:
<head>
<script type="text/javascript" src="quadratic.js"></script>
</head>
<body>
<form name="quadratic">
<input type="number" required="required" name="A">
<input type="number" required="required" name="B">
<input type="number" required="required" name="C">
<input type="button" value="Solve" onClick="solve()">
</form>
<p id="output">
</p>
</body>
This will create a web-page with three input fields and a button. The equation will be solved once the button is pressed, and the roots will be printed beneath the inputs.
JavaScript doesn’t provide complex numbers, so the calculations are done in real numbers with separate check for discriminant sign. This implementation allows to solve quadratic equations not only with integer coefficients but also with floating-point ones.
function print(real, imag)
{ if (Math.abs(imag)<1E-6)
return real;
else
return '('+real+','+imag+')';
}
function solve()
{ A = document.quadratic.A.value;
if (Math.abs(A)<1E-3)
{ document.getElementById('output').innerHTML = 'Not a quadratic equation';
return;
}
B = document.quadratic.B.value;
C = document.quadratic.C.value;
A = 2*A;
D = B*B-2*A*C;
if (Math.abs(D)<1E-3)
{ document.getElementById('output').innerHTML = 'x = '+(-B/A);
return;
}
if (D>0)
document.getElementById('output').innerHTML = 'x1 = '+print((-B+Math.sqrt(D))/A, 0)+'<br />x2 = '+print((-B-Math.sqrt(D))/A, 0);
else
document.getElementById('output').innerHTML = 'x1 = '+print(-B/A,Math.sqrt(-D)/A)+'<br />x2 = '+print(-B/A,-Math.sqrt(-D)/A);
}
Comments
]]>blog comments powered by Disqus
]]>