newtonraphson <- function(ftn, x0, tol = 1e-9, max.iter = 100) {
  #newton raphson algorithm for solving ftn(x)[1] == 0
  #x0 is starting point
  
  #initialise
  x <- x0
  fx <- ftn(x)
  iter <- 0
  
  #continue iteration until stopping condition
  while((abs(fx[1]) > tol) && (iter < max.iter)) {
    x <- x - fx[1]/fx[2]
    fx <- ftn(x)
    iter <- iter + 1
    cat("dar iteration", iter, "meghdare x:", x, "\n")
  } 
  
  #output
  if (abs(fx[1]) > tol) {
    cat("algorithm vagara shod\n")
    return(NULL)
  } else {
    cat("algorithm hamgera shod\n")
    return(x)
  }
}