0

Here is a program that asks the user for a number (variable r) to find the positive root of, and then asks for a starting interval [a,b]. This is done in some HTML code. The javascript below it has the code for linear interpolation inside a while loop.

function everything() {

r= document.getElementById('ri').value*1;
a= document.getElementById('ai').value*1;
b= document.getElementById('bi').value*1;

bisect(function(x){return x*x-r;},a,b);
}   

function bisect(f,a,b) {
var avg,fa,fb;

avg = NaN;
while (Math.abs(a-b)>1e-10) {
    fa=f(a);
    fb=f(b);
    if(fa*fb<0) {
            grad=(fb-fa)/(b-a);
        avg=a-(fa/grad);
        favg=f(avg);
    } else {
        alert('There has been an error. Redifine the interval A to B');
        break;
        }

    if (fa*favg<0) {
        b=avg;
     } else {
        a=avg;
    }
}
alert(avg);
}

The problem with this code is it returns the error text, and the final value for avg at the end. This is a problem.

Chris
  • 25
  • 6
  • In your first 3 lines, change the `*1` to `* 1.0`. – lurker Jul 27 '13 at 20:10
  • Solution:`while (Math.abs(a-b)>1e-5) { fa=f(a); fb=f(b); if (Math.abs(fa)<1e-10) { avg=a; break; } if (Math.abs(fb)<1e-10) { avg=b; break; } if(fa*fb<0) { grad=(fb-fa)/(b-a); avg=a-(fa/grad); favg=f(avg); //alert([a,fa,b,fb]) } else { alert('There has been an error. Redifine the interval A to B'); break; } if (fa*favg<0) { b=avg; } else { a=avg; } } alert(avg); }` – Chris Jul 27 '13 at 21:06
  • 3
    that's pretty hard to read. ;) You are allowed on this site to post your own Answer. Then you can format it. – lurker Jul 27 '13 at 22:24

1 Answers1

0

Chris said

while (Math.abs(a - b) > 1e-5) {
  fa = f(a);
  fb = f(b);
  if (Math.abs(fa) < 1e-10) {
    avg = a;
    break;
  }

  if (Math.abs(fb) < 1e-10) {
    avg = b;
    break;
  }

  if (fa * fb < 0) {
    grad = (fb - fa) / (b - a);
    avg = a - fa / grad;
    favg = f(avg);
    //alert([a,fa,b,fb])
  } else {
    alert("There has been an error. Redifine the interval A to B");
    break;
  }

  if (fa * favg < 0) {
    b = avg;
  } else {
    a = avg;
  }
}
alert(avg);
milahu
  • 2,447
  • 1
  • 18
  • 25