2012年5月16日 星期三

Transact-SQL 以蒙地卡羅模擬計算圓周率 (Calculate Circumference Ratio by Using Monte Carlo Simulation)


蒙地卡羅模擬是一種利用機率及統計理論來處理問題的一種方式。本文將說明如何以此法進行圓周率的計算:

1) 於第一象限中,取長度為 1 的正方形。

2) 以 (0,0) 為中心、1 為半徑,畫出半徑為 1 的圓形 (只看第一象限的部份)。


3) 以亂數產生 10000000 個點的 X、Y 座標 (X、Y 均小於 1)。

4) 若 X^2 + Y^2 < 1,則該點落在圓形內。

5) 第一象限的圓面積 : 正方型面積 應等於  落在圓形內的點數 : 總點數
=>  (PI * 1 * 1 * (1/4)) : (1 * 1) = 落在圓形內的點數 : 10000000
=>   PI = (落在圓形內的點數 / 10000000) * 4
即求得圓周率 PI


範例程式

declare @counter             bigint,
        @effective_counter   bigint,
        @pi                  float,
        @total_times         bigint,
        @x                   float,
        @y                   float
        

select @effective_counter = 0
select @total_times = 10000000
select @counter = 1

while @counter <= @total_times
 begin
    select @x = rand()
    select @y = rand() 

    if square(@x) + square(@y) <= 1
       select @effective_counter = @effective_counter + 1
 
    select @counter = @counter + 1
 end

select @pi = 4.0 * ((1.0 * @effective_counter) / (1.0 * @total_times))

select @pi as Result


計算結果

當隨機取點數目為:
(1).        100,000 時,所得結果 PI = 3.14372
(2).     1,000,000 時,所得結果 PI = 3.140452
(3).   10,000,000 時,所得結果 PI = 3.142144
(4). 100,000,000 時,所得結果 PI = 3.1415344