Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quadratic Equation Solver in JavaScript

Tags:

javascript

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) );
like image 690
Stardust Avatar asked Oct 31 '15 17:10

Stardust


People also ask

How do you write a program to solve quadratic equations?

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.

Where are the roots in a quadratic equation?

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.


2 Answers

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));
like image 66
Nina Scholz Avatar answered Oct 10 '22 01:10

Nina Scholz


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");
}
like image 30
Hari Mohan Avatar answered Oct 10 '22 01:10

Hari Mohan