I am trying to generate times from an inhomogeneous Poisson process having intensity function (lambda_time) as below-
lambda_time<-function(k,p,a,t){
k*(p-1)*(a^(p-1))*((t+a)^(-p))
}
. My code for generating "n" times between the interval (0,Tmax) is as follows-
Inhomogeneous<- function(lambda_time,n,k,p,a,tmax,lambdamax=NA){
if(is.na(lambdamax)){
lambdamax<- max(sapply(seq(0,tmax,length.out=2000),lambda_time,k=k,p=p,a=a))
}
t<-0
count<-1
times<-numeric()
times[1]<-t
while(times[length(times)]<tmax && count<=n){
e<-rexp(1,lambdamax)
t<-t+e
v<-runif(1)
if(t<tmax && v<=(lambda_time(k,p,a,t)/lambdamax)){
times<-c(times,t)
count<-count+1
}
}
return(times[-1])
}
. But the code is very slow. I do not understand why? Can anyone tell me? The values of k,p,a will be like 1.8,1.9,0.6 or something like these.
R runs best when variables are vectorized. Your programming style in reminiscent of low-level and assembly languages like C and Fortran, in which vectorization does not offer a significant speed improvement.
There are a few things you could do to reduce the amount of function calls and declarations in your code.
Use a for loop and control flow with a break statement.
for( i in 1:n ){
### do math here
if( times[length(times)] < tmax ) break
}
Pre-declare vectors and have R access them by index (even if you don't use every random number you generate)
v <- runif( n = n )
t <- rep(NA, n)
etc...
for( i in 1:n ){
### do math here
### access v as v[i]
if( times[length(times)] < tmax ) break
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.