approximationMethods.R

nesau — Mar 5, 2014, 10:19 AM

f <- function(x) {
  return (0.4*x^2 - 15.6*x + 56)
}

# use bisection algorithm to find the root of f
# search between a and b
# use 50 iterations for now
bisection <- function(f,a,b) {
  min = if(f(a)<0) a else b
  max = if(f(b)>0) b else a
  if (min==max) return(0)
  for (i in 1:50) {
    avg = (min+max)/2
    if(f(avg) < 0) min = avg 
    else max = avg
  }
  return(round(avg,5))
}

# approximate the derivative of a function evaluated at x
derivative <- function(f,x) {
  epsilon = 0.000001
  deriv = (f(x+epsilon)-f(x))/epsilon
  return(round(deriv,5))
}

newtons <- function(f,a,b) {
  xn = (a+b)/2  # initial guess
  n = 20        # number of iterations
  for (j in 1:n) {
    xn = xn - f(xn)/derivative(f,xn)
  }
  return(xn)
}

# return the roots of a quadratic equation
quadratic <- function(a,b,c) {
  if ((b^2 - 4*a*c)>=0) {
    return(c((-b+sqrt(b^2-4*a*c))/(2*a), (-b-sqrt(b^2-4*a*c))/(2*a)))
  }
  return(c(0,0))
}


ans = quadratic(0.4,-15.6,56)