(This article was first published on

**Freakonometrics - Tag - R-english**, and kindly contributed to R-bloggers)The following simple code can be used to find roots of functions (based on the secant algorithm),

secant=function(fun, x0, x1, tolerence=1e-07, niter=500){

for ( i in 1:niter ) {

x2 <- x1-fun(x1)*(x1-x0)/(fun(x1)-fun(x0))

if (abs(fun(x2)) < tolerence)

return(x2)

x0 <- x1

x1 <- x2

}}

It can be interesting in actuarial science, e.g. to find the actuarial rate so that to present values are equal. For instance, consider the following capital, given only if the insured is still alive (this example was initially considered here). We would like to find the rate so that the probable discounted value is 600,

> Lx=read.table("http://perso.univ-rennes1.fr/arthur.charpentier/TV8890.csv",

+ header=TRUE,sep=";")

> capital=c(100,100,125,125,150,150)

> n=length(capital)

> x=0.035

> X=45

> f=function(x){

+ capital.act=capital*(1/(1+x))^(1:n)

+ PROBA=Lx[((Lx[,1]>X)*(Lx[,1]<=(X+n)))==1,2]/Lx[(Lx[,1]==X)==1,2]

+ return(sum(capital.act*PROBA))}

>

> f1=function(x){f(x)-600}

> secant(f1,0,0.1)

[1] 0.06022313

> f(0.06022313)

[1] 600

To

**leave a comment**for the author, please follow the link and comment on their blog:**Freakonometrics - Tag - R-english**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...