Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Script to solve quadratic - help !

  1. Nov 29, 2007 #1
    Dear forum

    Please help - I am feeling very useless and depressed as something which worked years ago while at uni now seems to beat me !!

    I am trying to write a simple script (javascript actually) which calculates the root of a quadratic given two guesses of x (one guess giving y<0, the other giving y>0). From these values of x1 and x2 it calulates y at the mid-point, and depending on whether y is positive or negative it moves one of the boundaries half-way towards the midpoint.

    I will paste the code below. The program runs but doesn't converge:

    <script type="text/javascript">
    document.write("Solving the equation : 3x^2-5=0");
    x1 = window.prompt ("Enter a VERY LOW initial guess for x");
    x2 = window.prompt ("Now enter a VERY HIGH initial guess for x");

    while (Math.abs(y) >= 0.01)


    else if(y>0)



    I realise there are probably better ways of acheiving the same thing, but I'm sure this (or something very similar) used to work.

    Thank you in anticipation

    Matt Klein
  2. jcsd
  3. Nov 29, 2007 #2


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    You are doing a simple bisection medthod, not the fastest method, certianly a reliable one.

    You need to start with a check that you indeed have a root on your initial interval.

    so: [tex] f(x_1) * f(x_2) <0 [/tex] has to be true before you start the procedure.
    if xm is your mid point.

    check if [tex] f(x_1) * f(x_m) >0 [/tex] if true let [tex] x_1 = x _m [/tex]

    if false let [tex] x_2 = x_m [/tex]

    repeat until f(xm) is sufficient small.
  4. Nov 30, 2007 #3
    Thanks for your reply Integral

    It was especially useful to know the methods name (Bisection Method) as now I can look up all sorts of simple examples elsewhere on the net


  5. Dec 2, 2007 #4
    I am curious: why are you using the Bisection Method? And why are you writing your own script instead of using one of the many already available on the Internet?
  6. Dec 3, 2007 #5
    Hi Duncan

    Just for the sake of it really. It is some years since I wrote any code. Of course I could solve this sort of quadratic in seconds, but I wanted to revisit the bisection method and see if I could make it work!

    I am an A-level physics teacher so coding is not the sort of thing I would normally get round to doing

Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?

Similar Discussions: Script to solve quadratic - help !
  1. Quadratic Problem (Replies: 2)

  2. Quadratic Question (Replies: 4)