[Bayes] runif: Inversion Sampling

runifumhtml

Inversion Sampling 看樣子就是個路人甲。express

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) 算是一個表達技巧,將本來兩個半圖,合併在了一塊兒,以下:post


 

簡化技巧

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 Uurl

相關文章
相關標籤/搜索