假设概率密度函数为:
思路:
首先产生-1到1之间的均匀分布随机数x,和0到1之间的均匀分布随机数y。
如果y<f(x),则x是符合该概率密度的随机数,否则,重复上述操作。
用r语言生成100个随机数程序如下:
> for(i in 1:100)
+ {x[i]=runif(1,-1,1)
+ y[i]=runif(1,0,1)
+ while(y[i]>(1-abs(x[i])))
+ {x[i]=runif(1,-1,1)
+ y[i]=runif(1,0,1)
+ }
+ }
随机数如下:
> x
[1] -0.514901637 -0.217501164 0.711344072 0.392367283 0.630612312
[6] 0.546505700 0.586900601 -0.743232092 -0.336172141 -0.889316445
[11] -0.483111145 0.262203687 0.060877270 0.375244982 0.026205739
[16] 0.164838966 0.322126824 -0.595749320 0.174984953 0.437411303
[21] 0.411043267 -0.164316747 -0.448740647 0.398710048 0.387240598
[26] -0.377926981 -0.703300728 0.607546115 0.192999553 -0.018041003
[31] -0.020166740 0.499004755 -0.735728289 0.662798617 -0.244104174
[36] 0.360975237 -0.080959949 0.194795900 0.067130172 -0.150683799
[41] 0.196463150 -0.664764840 0.080320831 -0.537401136 0.103412358
[46] 0.113238147 -0.123515784 0.013652259 0.039734034 0.403804602
[51] 0.464418256 -0.378770977 -0.323632269 -0.536819858 -0.637694909
[56] -0.443880166 0.101090029 0.020091781 -0.043975835 -0.083350927
[61] -0.154194120 -0.161078955 0.582624681 -0.128034349 -0.129948552
[66] 0.505254598 0.492040237 0.729876905 -0.317929749 0.025999713
[71] 0.219295514 0.004028297 -0.020060018 0.434986595 -0.496682210
[76] 0.367210269 -0.075623044 -0.019082523 0.369629193 -0.122305395
[81] -0.063062626 -0.041233874 0.451531802 -0.171188537 -0.533768997
[86] 0.418290247 0.952854297 0.033798765 -0.069794761 -0.671866662
[91] 0.455189073 0.133429194 -0.785471270 0.351558574 -0.551275020
[96] 0.094082693 0.216529398 -0.195531629 -0.457623412 0.103529213
画图如下: