#generator of "num" Norwegian lives based on K2013 given that the
#insured is alive at a given age, using the inverse transform method.

source("K2013.r")
source("probabilityK2013.r")

#choose integration method
p.K13 <- function(n,m) p.K13.Rcubature(n,m)

life.gen <- function(age,num){
  x0 <- age
  life.inv <- function(y, lower=0, upper=120)
  uniroot( (function(x) 1-p.K13(0,x)-y), lower=lower, upper=upper )$root
  
  u <- runif(num,0,1)
  lives <- u
  for(i in 1:num){ lives[i] <- floor(life.inv(u[i])) }
  return(x0+lives)
}

#Checking that the generated values correspond to the distribution
#function of remaining life-times
age0 <- x0
G <- 0
R <- 0
Y <- 2023

y <- life.gen(age0,1000)
z <- rep(0,120)
for( i in age0:120){
z[i] <- 1-p.K13(0,i-age0)
print(z[i])
}

plot(ecdf(y), xlim=c(age0,120))
lines(z, col="red")
