Ladies_Man

#NumMeth Lab 4 (Newtons) COMPLETE

May 25th, 2016
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var eps = 0.001;
  2.  
  3. function f(x) { return x*x + x - 6; }
  4. function df(x) { return 2*x + 1; }
  5.  
  6. function sgn(x) {
  7.     if (x > 0) return 1;
  8.     if (x < 0) return -1;
  9.     return 0;
  10. }
  11.  
  12. function newtons(fx, dfx, x0) {
  13.     var x0, x1 = x0 - fx(x0)/dfx(x0);
  14.     var steps = 0;
  15.  
  16.     while (true) {
  17.  
  18.         x0 = x1;
  19.         x1 = x1 - fx(x1)/dfx(x1);
  20.  
  21.          if (0 == fx(x1))
  22.             break;
  23.  
  24.         if (fx(x1) * fx(x1 + sgn(x0 - x1)*eps) < 0)
  25.                 break;
  26.        
  27.         steps++;
  28.     }
  29.    
  30.     console.log("X=" + x1 + " steps=" + steps);
  31. }
  32.  
  33. function lab4Main() {
  34.     newtons(f, df, -7.5);
  35.     //newtons(f, df, 7.5);
  36. }
Advertisement
Add Comment
Please, Sign In to add comment