Monte Carlo estimation of PI


Author Message
Nimue

Guru

Joined: 06/08/2020
Location: United Kingdom
Posts: 427
Posted: 06:43pm 07 Sep 2020      

One of my goto (no pun intended) programming exercises for more advanced students is to devise a program to estimate PI -- there are many methods available for this, but one of my favourite is to draw a circle in a square (or more precisely 1/4 of a square / circle) and randomly fill with pixels.  Count the ratio of inside the circle to outside and you can estimate PI.

Today, after a couple of hours with students and the CMM2, we came up with this:

'Estimate PI with Monte Carlo Simulation

MODE 1,8  ' default screen settings

CLS

CONST POINTS = 100000  ' number of points to simulate.  More = higher accuracy and slower
CONST LENGTH = 450     ' length of square and radius of circle

text 250,25, "Monte Carlo Simulation to estimate PI"

BOX  ((800-LENGTH)/2)-5 ,(600-LENGTH)/2-4,LENGTH+10,LENGTH+10,4   ' bounding box, slightly larger than the area to draw in

ARC  (800-LENGTH)/2,(LENGTH+(600-LENGTH)/2),LENGTH-1,LENGTH,0,90   ' 1/4 circle, with same radius as square side

inside = 0   ' Reset counter for points inside circle


FOR i = 0 TO POINTS       ' iterate through the points
 x=INT(RND*(LENGTH+1))   ' random between 0 and Length (int rounds down)
 y=INT(RND*(LENGTH+1))
 d=SQR(x^2+y^2)          ' calculate the radius

 IF d <= LENGTH THEN    '  if inside the circle
   inside = inside +1
   PIXEL (x+(800-LENGTH)/2),(600-LENGTH)/2+LENGTH-y,RGB(red)
 ELSE
   PIXEL (x+(800-LENGTH)/2),(600-LENGTH)/2+LENGTH-y,RGB(green)
 ENDIF
NEXT i

header$="After " + STR$(POINTS) + " Iterations"
header2$="PI approximately = " + STR$(inside/POINTS * 4)

TEXT 300, 40, header$,,,,RGB(RED)
TEXT 280, 55, header2$,,,,RGB(GREEN)



The CMM2 will simulate upto 1,000,000 points in a reasonable time - and to be 100% honest, coding the display was far easier than the same exercise in Python - no libraries needed.


Thanks to pointers from @matherp regarding the scaling / aspect ratios (note to self - if you use the CMM2 via a HDMI capture card, remember to check the resolution / aspect ration of the window).

Nim