Javascript quadratic equation solver

Here is a simple javascript that solves quadratic equations of the form ax²+bx+c = O. You just have to specify the values of a ,b and c and the script then calculates the two real roots alpha(x1) and beta (x2)  of the equation. The script also tells you if the equation has a real root or not, depending upon the value of D (Discriminant). The equation is solved using the quadratic formula x = -b±(b²-4ac)½/2a .
The script is located here ->http://www.dynamicguru.com/files/quadratic_equation.html

Here is the source code of the script :

//Place this within the  section
<script type="text/javascript"><
function calculate()
    {
     var a=prompt("enter value of a");
     var b=prompt("enter value of b");
     var c=prompt("enter value of c");
     var a2=2*a;
     var ac=4*a*c;
     var dis=b*b;
     var dis=dis-ac;
     if(dis<0){
        document.getElementById('Equation').innerHTML='No real roots exist since Discriminant < 0 !<br />D = ' + dis + ' <br />The Equation = ' + a + 'x&#178; + ' + b + 'x + ' + c + '<br />';
        document.getElementById('x1').innerHTML='&nbsp; ';
        document.getElementById('x2').innerHTML='&nbsp; ';
        }
     else{
        var dis_sqrt=Math.sqrt(dis);
        var x1=-b+dis_sqrt;
        var x1=x1/a2;
        var x2=-b-dis_sqrt;
        var x2=x2/a2;
        document.getElementById('Equation').innerHTML=" Equation = " + a + "x&#178; + " + b + "x + " + c + "<br />";
        document.getElementById('x1').innerHTML=' Alpha (x1) = ' + x1;
        document.getElementById('x2').innerHTML=' Beta (x2) = ' + x2;
        }
    }
</script>

//Place this within the section:
<h1><a onclick="calculate()" href="#"> Click to solve »»</a></h1>
    <div id="Equation"></div>
    <div id="x1"></div>
    <div id="x2"></div>

Mujtaba

I am a student of Computer engineering and a freelance web designer and developer with a passion for interface design. WordPress is my framework of choice and I also build web and mobile applications. My Google+ Profile

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2013 All rights reserved | Powered by WordPress
Back to top ↑