Skip to content

Instantly share code, notes, and snippets.

@willtownes
Created November 7, 2012 21:46
Show Gist options
  • Save willtownes/4034716 to your computer and use it in GitHub Desktop.
Save willtownes/4034716 to your computer and use it in GitHub Desktop.
Example of recursion in R
#Example of using recursion to apply newton's method to an arbitrary function in order to find the zeros of the function. If no zeros are found after some number of iterations, NA is returned
newton.recursive<-function(func,deriv,counter=100,x=1,relchange=1){
diff = func(x)/deriv(x)
relchange = abs(diff/x)
if(counter==0){
print("Failed to converge")
return(NA)
}
else if(relchange <= 1e-10){
return(x)
}
else{
return(newton.recursive(func,deriv,counter=counter-1,x=x-diff,relchange))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment