close

1.前言:
在C#中產生亂數,用蒙地卡羅模擬方法求圓周率。

2.說明:

蒙地卡羅模擬是利用統計理論來處理數值分析問題,有關蒙地卡羅方法,可參考wiki的說明
http://en.wikipedia.org/wiki/Monte_Carlo_method

本範例是利用系統產生亂數,亂數產生的(x,y)點繪製在影像上,當點在圓內,標記為紅色,當點在圓外,標記為綠色。若圓面積與正方形面積的比例為A,可得到圓周率為4*A,因此可計算亂數點落在圓內與所有點的比例來估算近似圓周率。

程式碼:

private void MonteCarloSimulation()
{
	//定義影像檔
	Image img = new Bitmap(500, 500);
	//在image上繪圖
	Graphics g = Graphics.FromImage(img);
	//繪圖品質設定
	g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
	g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
	g.CompositingQuality = CompositingQuality.HighQuality;
	g.SmoothingMode = SmoothingMode.AntiAlias;
	g.InterpolationMode = InterpolationMode.High;
	//先將背景色設定為黑色
	g.FillRectangle(new SolidBrush(Color.FromArgb(30, 30, 30)), 0, 0, 500, 500);

	Random rnd = new Random();
	int cntInside = 0;
	int cntTotal = 100000;

	for (int i = 0; i < cntTotal; i++)
	{
		int posX = rnd.Next(0, 500);
		int posY = rnd.Next(0, 500);

		if ((Math.Pow((double)posX, 2) + Math.Pow((double)posY, 2)) <= Math.Pow(500, 2))//落在圓內
		{
			cntInside++;
			SolidBrush s = new SolidBrush(Color.FromArgb(255, 0, 0));
			RectangleF rec = new RectangleF(posX, posY, 1, 1);
			g.FillRectangle(s, rec);
		}
		else//落在圓外
		{
			SolidBrush s = new SolidBrush(Color.FromArgb(0, 255, 0));
			RectangleF rec = new RectangleF(posX, posY, 1, 1);
			g.FillRectangle(s, rec);
		}
	}

	//AreaRatio = pi*r^2/(2r)^2 = pi/4 ==> pi=4*AreaRatio
	Console.WriteLine("Simulation PI Value: {0}", (4.0 * (double)cntInside / (double)cntTotal).ToString());

	//顯示影像
	pictureBox1.Image = img;
}

繪圖:

MonteCarloSimulation  

arrow
arrow
    文章標籤
    C# MonteCarlo 圓周率
    全站熱搜

    西夏普 發表在 痞客邦 留言(0) 人氣()