Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Bisection<-function(func,x_left,x_right,accurary=0.001)
- {
- if (f(x_left) * f(x_right)>0){
- cat("Two end points have the same sign! Cannot use bisection\n")
- return
- }
- iter = 1
- while(x_right-x_left>accurary)
- {
- x_mid = (x_left+x_right)/2
- cat("Iteration ", iter, " x=", x_mid, "\n");
- iter=iter+1
- if (f(x_mid)*f(x_left)>0) { #mid has same sign as left, then search right
- x_left = x_mid
- } else {
- x_right = x_mid
- }
- }
- }
- Newton <-function(func, funcPrime, x ,accurary=0.001)
- {
- x_old = x
- iter = 1
- while(TRUE)
- {
- x_new = x_old - func(x_old)/funcPrime(x_old)
- cat("Iteration ", iter, " x=", x_new, "\n");
- if (abs(x_new - x_old)<accurary) {
- break;
- }
- if (abs(x_new-x_old)>1000) {
- cat("Newton's method seems to diverge\n");
- break;
- }
- if (iter>1000) {
- cat("No solution after 1000 iterations.\n");
- break;
- }
- x_old = x_new
- iter = iter+1
- }
- }
- f<-function(x) {return(x^3-x-2)}
- fprime<-function(x) {return(3*x^2-1)}
- Bisection(f,0,1)
- Newton(f,fprime,2)
- Newton(f,fprime,0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement