Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. newton_method <- function(f, df, x_0,
  2. stop_criteria = .Machine$double.eps,
  3. max_iter = 10^3,
  4. left_b = -Inf, right_b = Inf){
  5.  
  6. # criteria for starting point x_0
  7. if (left_b > x_0 | right_b < x_0){
  8. warning("your starting point is out of bound,
  9. please try point in the bounds")
  10. return(NA)
  11. }
  12.  
  13. # variable initialization
  14. iters <- 0
  15. x_1 <- 0
  16. distance <- Inf
  17.  
  18. # do while until
  19. # 1) x does not move
  20. # 2) exceed the maximun iteration
  21. # 3) the function value become close to zero
  22. while ((distance > stop_criteria) &
  23. (iters < max_iter) &
  24. (abs(f(x_0)) > stop_criteria)){
  25. # newton method
  26. x_1 <- x_0 - ( f(x_0) / df(x_0) )
  27.  
  28. # out of bound case
  29. if (x_1 <= left_b) {
  30. x_1 <- left_b
  31. }
  32. if (right_b <= x_1){
  33. x_1 <- right_b
  34. }
  35. distance <- abs(x_0 - x_1)
  36. iters <- iters + 1
  37. x_0 <- x_1
  38. }
  39.  
  40. # return the final point
  41. if (x_0 == left_b | x_0 == right_b){
  42. warning("\n", "Final point is on the boundary", "\n")
  43. }
  44. if (iters > max_iter){
  45. warning("\n", "Cannot find the root during the iteration.", "\n")
  46. }
  47. cat("Final value of function:", f(x_0), "\n")
  48. }
  49.  
  50. g <- function(x){ - sin(x)}
  51. out<-sapply(c(1,4,8), newton_method, f = cos, df = g)
  52. sol_plot<-data.frame(x_star=out,y_star=cos(out))
  53.  
  54.  
  55. library(ggplot2)
  56. x_grid<-seq(0,10,length.out = 200)
  57. df_plot<-data.frame(x=x_grid,y=cos(x_grid),zero=0)
  58.  
  59. ggplot(data=df_plot)+geom_line(aes(x=x,y=y),colour="blue")+
  60. geom_line(aes(x=x,y=zero),colour="black")+ theme_bw()+
  61. geom_point(data=sol_plot,aes(x=x_star,y=y_star),shape=4,size=5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement