Created
November 7, 2012 21:46
-
-
Save willtownes/4034716 to your computer and use it in GitHub Desktop.
Example of recursion in R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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