Click to See Complete Forum and Search --> : quadratic formula


z_mirza
01-20-2003, 08:54 PM
simple question... why doesnt this work?
it works for the equation 2x^2 - 16x = 30
but not for any thing else...

<script language="JavaScript">
function calculate()
{
var frmQ = document.quadratic;

frmQ.q1.value;
frmQ.q2.value;
frmQ.q3.value;

var varA = Number(frmQ.q1.value);
var varB = Number(frmQ.q2.value);
var varC = Number(frmQ.q3.value);

var sqrB = varB * varB;
var tndPart = 4 * varA * varC;
var last = 2 * varA;
var val = 0;
var val2 = 0;

var sqrtStmtVal = sqrB - tndPart;
var sqrtStmtVal2 = sqrB + (-1 * tndPart);

if (sqrtStmtVal < 0) sqrtStmtVal = sqrtStmtVal * -1;
if (varB < 0) varB = varB * -1;

var sqrtStmt = Math.sqrt(sqrtStmtVal);
val = varB + sqrtStmt;
val = val / last;
frmQ.sol.value = round(val);

if (sqrtStmtVal2 < 0) sqrtStmtVal2 = sqrtStmtVal2 * -1;

var sqrtStmt2 = Math.sqrt(sqrtStmtVal2);
val2 = (-1 * varB) + sqrtStmt2;
if (val2 < 0) val2 = val2 * -1;

val2 = val2 / last;
frmQ.sol2.value = round(val2);
}

function round(x)
{
return Math.round(x*100)/100;
}


</script>

z_mirza
01-21-2003, 03:28 PM
wow 19 views and no knows???

jeffmott
01-21-2003, 06:12 PM
You may not have received a reply because your code is a little difficult to follow.
Originally posted by z_mirza
var sqrtStmtVal = sqrB - tndPart;
var sqrtStmtVal2 = sqrB + (-1 * tndPart);
The first problem is that these two expressions compute to the same value. The second problem is that you need to negate the entire expression, not just the tndPart. And the third is that the negation needs to happen after you take the square root. As I said, the code is difficult to follow so I'm not going to find each spot that needs to be changed. But I can offer you a neater solution:

function quad(a, b, c, d) {
&nbsp; if (a == 0) return undefined;
&nbsp; var e = Math.pow(b, 2) - 4 * a * c + 4 * a * d;
&nbsp; if (e >= 0)
&nbsp; &nbsp; return [(-b + Math.sqrt(e)) / (2 * a), (-b - Math.sqrt(e)) / (2 * a)];
&nbsp; else
&nbsp; &nbsp; return NaN;
}

z_mirza
01-21-2003, 06:16 PM
EDIT: i fixed it

var e = Math.pow(varB, 2) - (4 * varA * varC);

if (e >= 0)
{
val = [(-varB + Math.sqrt(e)) / (2 * varA)];
frmQ.sol.value = round(val);

val2 = [(-varB - Math.sqrt(e)) / (2 * varA)];
frmQ.sol2.value = round(val2);
}

else
frmQ.sol.value = round(NaN);
frmQ.sol2.value = round(NaN);

}


thanx for all your help jeffmott, it means alot:)