For some reason, when a=1, b=1, c=-1, I am not getting the desired result of -1.6180339887499 and 0.61803398874989. Instead, I get 2 and 1. What am I doing wrong?
function solve(a,b,c){
var result = (((-1*b) + Math.sqrt(Math.pow(b,2)) - (4*a*c))/(2*a));
var result2 = (((-1*b) - Math.sqrt(Math.pow(b,2)) - (4*a*c))/(2*a));
return result + "<br>" + result2;
}
document.write( solve(1,1,-1) );
h> int main(void) { double a,b,c,root1,root2; printf(" Please enter a \n"); scanf("%lf",&a); printf(" Please enter b \n"); scanf("%lf",&b); printf(" Please enter c \n"); scanf("%lf",&c); if (b*b-4. *a*c>0) { root1 = (-b + sqrt(b*b-4.
Roots are also called x-intercepts or zeros. A quadratic function is graphically represented by a parabola with vertex located at the origin, below the x-axis, or above the x-axis. Therefore, a quadratic function may have one, two, or zero roots.
You need another grouping:
var result = (((-1 * b) + Math.sqrt(Math.pow(b, 2)) - (4 * a * c)) / (2 * a)); // wrong
var result2 = (((-1 * b) - Math.sqrt(Math.pow(b, 2)) - (4 * a * c)) / (2 * a)); // wrong
vs
var result = (-1 * b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a); // right
var result2 = (-1 * b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a); // right
All together:
function solve(a, b, c) {
var result = (-1 * b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
var result2 = (-1 * b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
return result + "<br>" + result2;
}
document.write(solve(1, 1, -1));
Try
var a, b, c, discriminant, root1, root2, r_Part, imag_Part;
document.write(realpart ="+r_Part" and imaganary part ="+imag_Part");
discriminant = b*b-4*a*c;
if (discriminant > 0)
{
root1 = (-b+sqrt(discriminant))/(2*a);
root2 = (-b-sqrt(discriminant))/(2*a);
document.write(real part ="+r_Part" and imaganary part ="+imag_Part");
}
else if (discriminant == 0)
{
root1 = root2 = -b/(2*a);
document.write(real part ="+r_Part" and imaganary part ="+imag_Part");
}
else
{
r_Part = -b/(2*a);
imag_Part = sqrt(-discriminant)/(2*a);
document.write(real part ="+r_Part" and imaganary part ="+imag_Part");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With