February 15, 2016

Excel VBAでモンテカルロシミュレーションを行い円周率を計算する

VBAで乱数を生成し、半径の中に存在するケースの数を数え上げることで円周率を求めるコード。
Sub pi()
    Dim xi As Double, yi As Double
    Dim radius As Double
    radius = 10
    
    Dim Iteration As Integer
    Iteration = 10000
    
    Dim CountInRadius As Integer
    CountInRadius = 0
    
    For i = 1 To Iteration
        xi = Math.Rnd * radius
        yi = Math.Rnd * radius
        
        If Math.Sqr(xi ^ 2 + yi ^ 2) < radius Then
            CountInRadius = CountInRadius + 1
        End If
    Next
    
    MsgBox "pi = " & CountInRadius / Iteration * 4
End Sub

No comments :

Post a Comment