Quadratic Equation Solver
Description: This script will factor and solve for both values of X, any quadratic equation that has real number solutions.
/* This script and many more are available free online at The JavaScript Source :: http://javascript.internet.com Created by: Ben Kanaev :: http://www.webhostreview.biz */ var a,b,c,x1,x2; function getValues() { signB = (document.form.firstSign.value == "+") ? 1 : -1; signC = (document.form.secondSign.value == "+") ? 1 : -1; a = document.form.x2Coef.value; b = document.form.xCoef.value * signB; c = document.form.endValue.value * signC; } function solveForX() { x1 = ((-1*b) + Math.sqrt((b*b) - 4*a*c))/ (2*a); x2 = ((-1*b) - Math.sqrt((b*b) - 4*a*c))/ (2*a); if(document.form.round.checked){ x1 = Math.round(x1*1000)/1000; x2 = Math.round(x2*1000)/1000; } } function factorEq() { if( (Boolean(x1) != false) && (Boolean(x2) != false)) { x1Print = ((x1 * -1) > 0) ? "+" + (x1*-1) : x1 * -1; x2Print = ((x2 * -1) > 0) ? "+" + (x2*-1) : x2 * -1; aPrint = (a > 1 || a < 0) ? a : ""; document.getElementById('testing').innerHTML = "The Solutions Are: x1 = " + x1 + "; x2 = " + x2 + " The Equation Is: " + aPrint + "(x " + x1Print + ") (x " + x2Print + ")"; } else { document.getElementById('testing').innerHTML = "YOUR INPUT PRODUCED AN ERROR: You have entered a non-integer into one of the fields above, or the solution(s) for your equation is(are) an imaginary(s) number!"; } } function SolveEq() { getValues(); solveForX(); factorEq(); }
The Solution Will Appear Here!
|