I would like to solve a nonlinear eqn using newton method and here is the code:
library(numDeriv)
fprime <- function(z)
{ alp <- 2.0165;
rho <- 0.868;
# simplified expressions
a <- alp-0.5
c1 <- sqrt(pi)/(gamma(alp)*(1-rho)^alp)
c2 <- sqrt(rho)/(1-rho)
t1 <- exp(-z/(1-rho))
t2 <- (z/(2*c2))^a
bes1 <- besselI(z*c2,a)
t1bes1 <- t1*bes1
c1*t1bes1*t2
}
## Newton iteration
newton_gam <- function(z)
{ n <- length(z)
r <- runif(n)
tol <- 1E-6
for (i in 1:n)
{ # numerical intergration to find the cdf
cdf[i] <- integrate(fprime, lower = 0, upper = z[i])$val
# Newton method
z[i] <- z[i] - (cdf[i] - r[i])/fprime(z[i])
}
z
}
z <- c(0.5,10,20,30)
newton_gam(z)
Output> z <- c(0.5,10,20,30)
> newton_gam(z)
[1] 4.498542e-01 -2.543392e+01 -4.031082e+03 -5.227064e+05
My question is how do I use ‘for’ and ‘while’ statement so that I can ask it to
repeat until it reaches certain tolerance and for a certain number of times.
Thank you.
[[alternative HTML version deleted]]