# VB Monte Carlo RNG Example

← All NMath Code Examples

```Imports System

Imports CenterSpace.NMath.Core

Namespace CenterSpace.NMath.Core.Examples.VisualBasic

' A .NET example in Visual Basic showing how to calculate an approximation for Pi using a Monte
' Carlo method and the uniform random number generator class RandGenUniform.
'
' Imagine a 2 x 2 square with corners at (1,1), (1,-1), (-1,-1) and (-1,1)
' and a unit circle, centered on the origin, inscribed within it. Generate
' random points inside the square and let M be the number of points
' that fall within the unit circle and N be the total number of points
' generated. As the number N gets large, the quantity M/N should approximate the
' ratio of the area of the circle to the square, which is pi/4. Hence, we can
' use the ratio 4*M/N to approximate Pi.
Module MonteCarloRNGExample

Sub Main()

' Construct a random number generator that generates random deviates
' distributed uniformly over the interval [-1,1]
Dim Rng As New RandGenUniform(-1.0, 1.0)

' We'll approximate pi to within 5 digits.
Dim Tolerance As Double = 0.00001

Dim PiApproximation As Double = 0
Dim total As Integer = 0
Dim NumInCircle As Integer = 0
Dim X, Y As Double ' Coordinates of the random point.

' Generate random points until our approximation within
' the desired tolerance.
While (Math.Abs(Math.PI - PiApproximation) > Tolerance)
X = Rng.Next()
Y = Rng.Next()
If (X * X + Y * Y <= 1.0) Then ' Is the point in the circle?
NumInCircle = NumInCircle + 1
End If

total = total + 1
PiApproximation = 4.0 * (CType(NumInCircle, Double) / CType(total, Double))
End While

Console.WriteLine()
Console.Write("Pi calculated to within " + Math.Abs(Math.Log10(Tolerance)).ToString())
Console.WriteLine(" digits with " + total.ToString() + " random points.")
Console.WriteLine("Approximated Pi = " + PiApproximation.ToString())

Console.WriteLine()
Console.WriteLine("Press Enter Key")