fun=function(x){x^3-6*x^2+11*x-5.9}
dfun=function(x){3*x^2-12*x+11}
fun(3.5)
## [1] 1.975
a=2.5
b=3.5
Bisection <- function(f, a, b, n = 3, tol = 1e-7) {
  if (!(f(a) < 0) && (f(b) > 0)) {
    stop('The root does not exist within this interval')
  } else if (!(f(a) > 0) && (f(b) < 0)) {
    stop('The root does not exist within this interval')
  }
  for (i in 1:n) {
    c <- (a + b) / 2
    if ((f(c) == 0) || ((b - a) / 2) < tol) {
      return(c)
    }
    ifelse(sign(f(c)) == sign(f(a)), 
           a <- c,
           b <- c)
  }
  print('Too many iterations')
  return(c)
}
Bisection(fun,a,b)
## [1] "Too many iterations"
## [1] 2.875
nrm = function(f, df, x0){
  n = 0
  while(n < 100){
  n = n+1
  y0 = f(x0)
  y1 = df(x0)
  if(y1 < 0.0001){
    break(0)
  }
  x1 = x0 - (y0/y1)
  if(abs((x0-x1)/x1)<0.0001){
    print("The point converges here")
    
    break(0)
  }
  
  x0 = round(x1,4)
  print(paste("Iteration" ,n, "is",x0))
  }
}
nrm(fun,dfun,b)
## [1] "Iteration 1 is 3.1565"
## [1] "Iteration 2 is 2.9937"
## [1] "Iteration 3 is 2.9491"
## [1] "Iteration 4 is 2.9457"
## [1] "The point converges here"
secant.method <- function(f, x0, x1, tol = 1e-9, n = 3) {
  for (i in 1:n) {
    x2 <- x1 - f(x1) / ((f(x1) - f(x0)) / (x1 - x0)) # Calculate the new x value
    if (abs(x2 - x1) < tol) { # If the difference between the new value and the previous value is small enough, end iteration and output root.
      return(x2)
    }
    # If the root was not determined in the previous iteration, update the values and proceed to the next iteration.
    x0 <- x1
    x1 <- x2 
  }
  return(x2)
}
secant.method(fun,a,b)
## [1] 3.366949
regula.falsi <- function(f, a, b, e = 1e-6, NMAX = 3, plot = FALSE, title = NULL) {
  # Input validation
  if (a >= b) stop("'a' must be less than 'b'")
  if (f(a) * f(b) >= 0) stop("Function must have opposite signs at endpoints")
  
  from <- a
  to <- b
  
  # Initialize variables
  fa <- f(a)
  fb <- f(b)
  root_history <- numeric(NMAX)
  
  # Main iteration loop
  for (i in 1:NMAX) {
    # Calculate new point using false position formula
    p <- b - fb * (b - a) / (fb - fa)
    root_history[i] <- p
    fp <- f(p)
    
    # Check for convergence
    if (abs(fp) < e) {
      if (plot) {
        # Use plot_root function for visualization
        plot_root(f, from, to, root = p, title = title)
        
        # Add iteration points in a different color
        points(root_history[1:i], rep(0, i), 
               col = "darkorange", pch = 1, lwd = 1)
      }
      return(p)
    }
    
    # Update interval
    if (fp * fb < 0) {
      a <- b
      fa <- fb
    }
    b <- p
    fb <- fp
  }
  return(p)
}
regula.falsi(fun,a,b)
## [1] 2.81491