精華區beta Mathematica 關於我們 聯絡資訊
※ 引述《bewilderment (發燒夏天)》之銘言: : 想請問版上高手, : 如果我想要用Mathematica來寫一個程式, : 可以一次讀兩個數x和p,x表示隨機變數的值, : p表示x的機率,然後可以重複這樣的步驟 : 直到某個終止條件產生,最後顯示這個隨機變數。 : 因為最近最近在學C語言而Mathematica有一段時間沒碰 : 蠻生疏的。現在腦袋裡都是二維陣列的作法....冏 : 所以想來版上求教一下。 : 另外我擔心我的中文沒有表達得很清楚, : 以下附上習題的原文: : Write a command in Mathematica which can take as input : a list of pairs {Pi,Xi} in which a random variable X takes : on value Xi with probability Pi and return the expectation : of X. : 最後感謝您的閱讀,謝謝。 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] (* random sample *) sample[n_]:= RandomChoice[dist[[All,2]]->dist[[All,1]]]&/@Range[n]; (* simulation *) 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] -- 養花種魚數月亮賞星星 http://chungyuandye.twbbs.org -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.173.132.66
bewilderment:超強.......太感謝大大了。 07/04 09:42