Generating random numbers from the Laplace distribution
I have been trying to generate random numbers from the double exponential(Laplace) distribution. I am at a point I can write the code anymore. Any help would be appreciated. The code below is what I have written.
rlaplace = function(u,a,b){
    u = c(runif(ns))
    for(i in 1:ns){
        if(u[i] <= 0.5){
            X = a+b*log(2*u)
        } else{
            X = a-b*log(2*(1-u))
        }
    }
    X
}
z1 = rlaplace(u,a,b)
From the Probability distributions CRAN Task View, there are several packages that already implement the Laplace distribution, notably distr and Runuran.
 So you should be able to install distr , for example, and do something like :  
library(distr)
D <- DExp(rate = 1) 
r(D)(1)
 Code taken from the examples of the DExp-class help page.  
尝试这个?
#Using pdf for a laplace RV:
#F(y) = 1/sqrt(2*sigma^2)*exp(sqrt(2)*abs(y-mu)/sigma)
rlaplace = function(n,mu,sigma){
  U = runif(n,0,1)
  #This will give negative value half of the time
  sign = ifelse(rbinom(n,1,.5)>.5,1,-1)     
  y = mu + sign*sigma/sqrt(2)*log(1-U)  
  y
}
上一篇: 用于实际随机/测试数据生成的数据集
下一篇: 从拉普拉斯分布生成随机数
