How to resolve the algorithm Monte Carlo methods step by step in the BASIC programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Monte Carlo methods step by step in the BASIC programming language

Table of Contents

Problem Statement

A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for

π

{\displaystyle \pi }

. If you had a circle and a square where the length of a side of the square was the same as the diameter of the circle, the ratio of the area of the circle to the area of the square would be

π

/

4

{\displaystyle \pi /4}

. So, if you put this circle inside the square and select many random points inside the square, the number of points inside the circle divided by the number of points inside the square and the circle would be approximately

π

/

4

{\displaystyle \pi /4}

.

Write a function to run a simulation like this, with a variable number of random points to select. Also, show the results of a few different sample sizes. For software where the number

π

{\displaystyle \pi }

is not built-in, we give

π

{\displaystyle \pi }

as a number of digits:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Monte Carlo methods step by step in the BASIC programming language

Source code in the basic programming language

DECLARE FUNCTION getPi! (throws!)
CLS
PRINT getPi(10000)
PRINT getPi(100000)
PRINT getPi(1000000)
PRINT getPi(10000000)

FUNCTION getPi (throws)
	inCircle = 0
		FOR i = 1 TO throws
			'a square with a side of length 2 centered at 0 has
			'x and y range of -1 to 1
			randX = (RND * 2) - 1'range -1 to 1
			randY = (RND * 2) - 1'range -1 to 1
			'distance from (0,0) = sqrt((x-0)^2+(y-0)^2)
			dist = SQR(randX ^ 2 + randY ^ 2)
			IF dist < 1 THEN 'circle with diameter of 2 has radius of 1
				inCircle = inCircle + 1
			END IF
		NEXT i
	getPi = 4! * inCircle / throws
END FUNCTION


# Monte Carlo Simulator
# Determine value of pi
# 21010513


tosses = 1000
in_c = 0
i = 0

for i = 1 to tosses
     x = rand
     y = rand
     x2 = x * x
     y2 = y * y
     xy = x2 + y2
     d_xy = sqr(xy)
     if d_xy <= 1 then
         in_c += 1
     endif
next i

print float(4*in_c/tosses)


print " Number of throws   Ratio (Pi)      Error"

for pow = 2 to 8
	n = 10 ^ pow
	pi_ = getPi(n)
	error_ = 3.141592653589793238462643383280 - pi_
	print rjust(string(int(n)), 17); "   "; ljust(string(pi_), 13); "   "; ljust(string(error_), 13)
next
end

function getPi(n)
	incircle = 0.0
	for throws = 0 to n
		incircle = incircle + (rand()^2 + rand()^2 < 1)
	next
	return 4.0 * incircle / throws
end function

      PRINT FNmontecarlo(1000)
      PRINT FNmontecarlo(10000)
      PRINT FNmontecarlo(100000)
      PRINT FNmontecarlo(1000000)
      PRINT FNmontecarlo(10000000)
      END
      
      DEF FNmontecarlo(t%)
      LOCAL i%, n%
      FOR i% = 1 TO t%
        IF RND(1)^2 + RND(1)^2 < 1 n% += 1
      NEXT
      = 4 * n% / t%


' version 23-10-2016
' compile with: fbc -s console

Randomize Timer  'seed the random function

Dim As Double x, y, pi, error_
Dim As UInteger m = 10, n, n_start, n_stop = m, p

Print
Print " Mumber of throws  Ratio (Pi)     Error"
Print

Do
    For n = n_start To n_stop -1
        x = Rnd
        y = Rnd
        If (x * x + y * y) <= 1 Then p = p +1
    Next
    Print Using "    ############,  "; m ;
    pi = p * 4 / m
    error_ = 3.141592653589793238462643383280 - pi
    Print RTrim(Str(pi),"0");Tab(35); Using "##.#############"; error_
    m = m * 10
    n_start = n_stop
    n_stop = m
Loop Until m > 1000000000 ' 1,000,000,000


' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End

 for pow = 2 to 6
    n = 10^pow
    print n, getPi(n)
next

end

function getPi(n)
    incircle = 0
    for throws=0 to n
        scan
        incircle = incircle + (rnd(1)^2+rnd(1)^2 < 1)
    next
    getPi = 4*incircle/throws
end function

10 mode 1:randomize time:defint a-z
20 input "How many samples";n
30 u=n/100+1
40 r=100
50 for i=1 to n
60 if i mod u=0 then locate 1,3:print using "##% done"; i/n*100
70 x=rnd*2*r-r
80 y=rnd*2*r-r
90 if sqr(x*x+y*y)<r then m=m+1
100 next
110 pi2!=4*m/n
120 locate 1,3
130 print m;"points in circle"
140 print "Computed value of pi:"pi2!
150 print "Difference to real value of pi: ";
160 print using "+#.##%"; (pi2!-pi)/pi*100

for pow = 2 to 6
    n = 10 ^ pow
    print n; chr$(9); getPi(n)
next 
end

function getPi(n)
    incircle = 0
    for throws = 0 to n
        incircle = incircle + (rnd(1)^2 + rnd(1)^2 < 1)
    next
    getPi = 4 * incircle / throws
end function

FUNCTION getpi(throws)
    LET incircle = 0
    FOR i = 1 to throws
        !a square with a side of length 2 centered at 0 has
        !x and y range of -1 to 1
        LET randx = (rnd*2)-1     !range -1 to 1
        LET randy = (rnd*2)-1     !range -1 to 1
        !distance from (0,0) = sqrt((x-0)^2+(y-0)^2)
        LET dist = sqr(randx^2+randy^2)
        IF dist < 1 then          !circle with diameter of 2 has radius of 1
           LET incircle = incircle+1
        END IF
    NEXT i
    LET getpi = 4*incircle/throws
END FUNCTION

CLEAR
PRINT getpi(10000)
PRINT getpi(100000)
PRINT getpi(1000000)
PRINT getpi(10000000)
END


OpenConsole()
 
Procedure.d MonteCarloPi(throws.d)
	inCircle.d = 0
		For i = 1 To throws.d
			randX.d = (Random(2147483647)/2147483647)*2-1
			randY.d = (Random(2147483647)/2147483647)*2-1 
			dist.d  = Sqr(randX.d*randX.d + randY.d*randY.d)
			If dist.d < 1 
				inCircle = inCircle + 1
			EndIf
		Next i
	pi.d = (4 * inCircle / throws.d)	
	ProcedureReturn pi.d
	
EndProcedure

PrintN ("'built-in' #Pi         = " + StrD(#PI,20))
PrintN ("MonteCarloPi(10000)    = " + StrD(MonteCarloPi(10000),20))
PrintN ("MonteCarloPi(100000)   = " + StrD(MonteCarloPi(100000),20))
PrintN ("MonteCarloPi(1000000)  = " + StrD(MonteCarloPi(1000000),20))
PrintN ("MonteCarloPi(10000000) = " + StrD(MonteCarloPi(10000000),20))

PrintN("Press any key"): Repeat: Until Inkey() <> ""

  

You may also check:How to resolve the algorithm CRC-32 step by step in the PowerBASIC programming language
You may also check:How to resolve the algorithm Bitmap/Bézier curves/Cubic step by step in the Racket programming language
You may also check:How to resolve the algorithm Short-circuit evaluation step by step in the Nanoquery programming language
You may also check:How to resolve the algorithm Loops/Continue step by step in the REXX programming language
You may also check:How to resolve the algorithm Ranking methods step by step in the AWK programming language