Advertisement
Guest User

Untitled

a guest
Jul 10th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.03 KB | None | 0 0
  1.  
  2. Bisection<-function(func,x_left,x_right,accurary=0.001)
  3. {
  4.     if (f(x_left) * f(x_right)>0){
  5.         cat("Two end points have the same sign! Cannot use bisection\n")
  6.         return
  7.     }
  8.     iter = 1
  9.     while(x_right-x_left>accurary)
  10.     {
  11.         x_mid = (x_left+x_right)/2
  12.         cat("Iteration ", iter, " x=", x_mid, "\n");
  13.         iter=iter+1
  14.         if (f(x_mid)*f(x_left)>0) { #mid has same sign as left, then search right
  15.             x_left = x_mid
  16.         } else {
  17.             x_right = x_mid
  18.         }
  19.     }
  20. }
  21. Newton <-function(func, funcPrime, x ,accurary=0.001)
  22. {
  23.     x_old = x
  24.     iter = 1
  25.     while(TRUE)
  26.     {
  27.         x_new = x_old - func(x_old)/funcPrime(x_old)
  28.         cat("Iteration ", iter, " x=", x_new, "\n");
  29.         if (abs(x_new - x_old)<accurary) {
  30.             break;
  31.         }
  32.         if (abs(x_new-x_old)>1000) {
  33.             cat("Newton's method seems to diverge\n");
  34.             break;
  35.         }
  36.         if (iter>1000) {
  37.             cat("No solution after 1000 iterations.\n");
  38.             break;
  39.         }
  40.         x_old = x_new
  41.         iter = iter+1
  42.     }
  43. }
  44. f<-function(x) {return(x^3-x-2)}
  45. fprime<-function(x) {return(3*x^2-1)}
  46. Bisection(f,0,1)
  47. Newton(f,fprime,2)
  48. Newton(f,fprime,0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement