2008年3月19日 星期三

隨機變數的產生

電腦裡面的亂數產生器可以產生[1 ~ RandMAX]範圍內的數字,我們可以把它視為是一個Uniform Distribution的產生器。如果我們在模擬的過程需要使用到其他機率分佈的產生器則需要使用以下的過程:

假設我們需要產生一個連續的r. v. X,其具有distribution function F

F 是嚴格遞增的函數(strictly increasing), i.e., if x1 <= x2, then 0 < F(x1) <= F(x2) <1。
令invF表示 F 的反函數,則產生X的隨機變數的程序為:

1. Generate U ~ U(0, 1)
2. Return X = invF(U)

remark: P(X <= x) = P(invF(U) <= x) = P(U <= F(x)) = F(x)


Examle. Let X have the exponential distribution with mean a. The distribution function is

F(x) = 1 - exp{ -x/a }, if x >= 0; 0, otherwise

so invF(u) = -aln(1 - u)

程式碼


Truncated density

考慮一個狀況,我們想要使用程式產生網路封包的大小(size)用來模擬網路的效能,通常可以假設封包的大小是依據exponential distribution。不過網路上的封包不會無限大,也不可能是0,所以需要限定所產生出來封包的上下限。How to do it?

define the truncated density

f*(x) = f(x) / (F(b) - F(a)), if a <= x <= b; 0, otherwise

the corresponding truncated distribution function is

F*(x) = ((F(x) - F(a)) / ((F(b) - F(a)), if a <= x <= b; 0, if x < a; 1, if b < x

The algorithm for generating an X having distribution function F* is as follows:
1. Generate U ~ U(0, 1).
2. Let V = F(a) + [F(b) - F(a)]U.
3. Return X = invF(V)


有兩個問題給你們想想:
1. 經過裁剪以後,mean與variance的改變為何?
2. 為何上述演算法的第三項是X = invF(V) 而不是X = invF*(V)?

NS2中的亂數產生器
NS2目前提供Pareto, Constant, Uniform, Exponential, 和 HyperExponintial分佈,程式碼放在
~/ns-allinone-2.29/ns-2.29/tools目錄下。

NS2中使用的方法:
1. 設定seed
set rng [new RNG]
$rng seed 1

2. 設定分佈
a. Pareto :
set r1 [new RandomVariable/Pareto]
$r1 use-rng $rng
$r1 set avg_ 10.0
$r1 set shape_ 1.2

b. Constant :
set r2 [new RandomVariable/Constant]
$r2 use-rng $rng
$r2 set avg_ 10.0


c. Uniform :
set r3 [new RandomVariable/Uniform]
$r3 use-rng $rng
$r3 set min_ 0.0
$r3 set max_ 10.2


d. Exponential :
set r4 [new RandomVariable/Exponential]
$r4 use-rng $rng
$r4 set avg_ 10.0


e. Hyperexponential :
set r5 [new RandomVariable/HyperExponential]
$r5 use-rng $rng
$r5 set avg_ 1.0
$r5 set cov_ 5.0

沒有留言: