Estimation of Pi by the Monte Carlo method

Contributions to this software library are always welcome. Please ensure that you post program listings rather than .raw files. They give a reasonable idea of what your program does without having to load them into a DM42 and you can also include comments in your code. Check out the following link for a decoder/encoder:

You can then copy/paste the listing and post it in "code" tags.
Post Reply
User avatar
Posts: 33
Joined: Fri Feb 12, 2021 1:00 am

Estimation of Pi by the Monte Carlo method

Post by ratwolf »

PiMC.png (1.45 KiB) Viewed 1916 times

Simulation of random (x, y) points in a unit square as a domain and a unit circle within the same domain inscribed in the unit square. The ratio of the number of points within the circle and the total number of points generated is then calculated, multiplied by 4

Please use in 4STK mode. Enter the number of loops. Press R/S. The estimate of Pi is then displayed in X.

Not bad: with Mathematica on my MacBook Pro, this takes about 50 seconds:

approxPi[n_] := 4. Count[Map[Norm, RandomReal[{-1, 1}, {n, 2}]], _?(# <= 1 &)]/n

With Free42 for Mac (v. 3.0.3, binary version) with 10^8 loops and the code shown below, it takes about 90 seconds.

Code: Select all

00 { 97-Byte Prgm }
01▸LBL "PiMC"
02 0
04 STO "Circle"
05 STO "Square"
06 INPUT "Loop"
07▸LBL 01
08 RAN
09 X↑2
10 RAN
11 X↑2
12 +
13 1
14 X<Y?
15 GTO 02
16 STO+ "Circle"
17▸LBL 02
18 STO+ "Square"
19 STO- "Loop"
20 0<? "Loop"
21 GTO 01
22 4
23 RCL× "Circle"
24 RCL÷ "Square"
25 END
(100 Bytes) Downloaded 40 times
Post Reply