6. Lua で作ってみる
zipfr.lua
euGm = 0.5772156649
max = 1000
count = 1000000
harm = math.log(max)+euGm
math.randomseed(os.time())
hist = {}
for i = 1, max, 1 do hist[i] = 0 end
for i = 1, count, 1 do
x = math.ceil(math.exp((math.random()*harm)-euGm))
hist[x] = hist[x]+1
end
for i = 1, max, 1 do print(i, hist[i]/count, 1/i/harm) end
6 / 10
8. 定義域と値域
一様乱数の入力 x = [0, 1) に対して、
出力 y = G (x; N) は y = [0, N) であって欲しい
しかし、G (0; N) = e −γ 、G (1; N) = N
だから1番目の値が小さかった!
値域の始まりを合わせるため、
G (x; N) = exp((log(N) + γ)x − γ) − e −γ とする
すると今度は値域の終わりが G (1; N) = N − e −γ とズレる
さらに値域の終わりを合わせるため、
G (x; N) = exp((log(N + e −γ ) + γ)x − γ) − e −γ とする
これで G (0; N) = 0、G (1; N) = N になった!
8 / 10
9. Lua で再実装
zipfrand.lua
euGm = 0.5772156649
max = 1000
count = 1000000
base = math.exp(-euGm)
harm = math.log(max)+euGm
cond = math.log(max+base)+euGm
math.randomseed(os.time())
hist = {}
for i = 1, max, 1 do hist[i] = 0 end
for i = 1, count, 1 do
x = math.ceil(math.exp((math.random()*cond)-euGm)-base)
if (x == 0) then x = 1 end
hist[x] = hist[x]+1
end
for i = 1, max, 1 do print(i, hist[i]/count, 1/i/harm) end
9 / 10