dist={{1,0.4},{4,0.1},{5,0.3},{8,0.03},{9,0.11},{10,0.06}};
ans[data_List]:={RandomChoice[data[[All,2]]->data[[All,1]]],
Plus@@Times@@@data}
ans[dist]
(* 產生樣本數為n的隨機樣本 *)
sample[n_]:=RandomChoice[dist[[All,2]]->dist[[All,1]]]&/@Range[n];
(* 輸出條型圖 *)
mychart[n_]:=Block[{temp},
temp=SortBy[Tally@sample[n],First];
BarChart[temp[[All,2]],
ChartLabels->temp[[All,1]],
LabelingFunction->(Placed[NumberForm[N[#/n],{4,3}],Above]&)]
];
mychart[100000]
(* 中央極限定理,每次抽n個樣本,重覆實驗m次 *)
sim[n_,m_]:=N@Mean[sample[n]]&/@Range[m]
GraphicsGrid@Partition[Histogram[sim[#,100],
PlotRange->{{2,6},Automatic},
AxesOrigin->{0,0}]&/@{10,100,500,1000},2]
Mathematica 教學:隨機樣本
由 戴忠淵 於 2012年7月4日星期三
上午9:32 發表
讀者回應 ( 0 意見 )
訂閱發佈留言 (Atom)
發佈留言
Please leave your name and tell me what you thought about this site. Comments, suggestions and views are welcomed.
如果這篇文章對你有幫助,那請留個訊息給我~