[Bayes] runif: Inversion Sampling
runifum
Inversion Sampling 看样子就是个路人甲。
Ref: [Bayes] Hist & line: Reject Sampling and Importance Sampling
> func=function(n) {
+ return(-0.5+sqrt(0.25+2*runif(n)))
+ }
// 反函数的x的均匀sampling值 => y 就是原函数的x,刚好作为hist的输入参数
> hist(func(5000),probability=T, xlab=expression(theta), ylab="Density", main="Samples from f(x)")
// 以下是真实值,用线表示
> xx=seq(0, 1, length=100)
> lines(xx, xx+0.5, col=2)
func=function(n) {
u=runif(n)
return(c(0.5*log(2*u[u<0.5]),-0.5*log(2*(1-u[u>0.5]))) )
}
hist(func(5000),probability=T,xlab=expression(theta),ylab="Density",main="Samples from f(x)",nclass=31,ylim=c(0,1))
xx=seq(-5,5,length=100)
lines(xx,exp(-sign(xx)*2*xx),col=2)
-sign(xx) 算是一个表达技巧,将原本两个半图,合并在了一起,如下:
简化技巧
Y = −λ log(1 − U ).
Note that if U is uniformly distributed on [0, 1], then 1 − U is also uniformly distributed on [0, 1] so that we could simply compute
Y = −λ log U