Script to solve quadratic - help

  • Context: Undergrad 
  • Thread starter Thread starter mklein
  • Start date Start date
  • Tags Tags
    Quadratic
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 3K views
mklein
Messages
43
Reaction score
0
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 realize 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
 
Physics news on Phys.org
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.
 
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

Cheers

Matt
 
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?
 
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