# Script to solve quadratic - help !

1. Nov 29, 2007

### mklein

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:

<html>
<body>
<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");
x=(x1+x2)/2;
y=3*x^2-5;
document.write(y);

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

if(y<0)
{x1=(x+x1)/2;
}

else if(y>0)
{x2=(x+x2)/2;
}

x=(x1+x2)/2;
y=3*x^2-5;

document.write(x1);
document.write(x2);
document.write(y);
}
</script>
</body>
</html>

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. Nov 29, 2007

### Integral

Staff Emeritus
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: $$f(x_1) * f(x_2) <0$$ has to be true before you start the procedure.
if xm is your mid point.

check if $$f(x_1) * f(x_m) >0$$ if true let $$x_1 = x _m$$

if false let $$x_2 = x_m$$

repeat until f(xm) is sufficient small.

3. Nov 30, 2007

### mklein

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

Cheers

Matt

4. Dec 2, 2007

### DuncanM

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?

5. Dec 3, 2007

### mklein

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

Matt