## 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: https://technical.swissmicros.com/decoders/dm42/

You can then copy/paste the listing and post it in "code" tags.
ratwolf
Posts: 26
Joined: Fri Feb 12, 2021 1:00 am

### Estimation of Pi by the Monte Carlo method

PiMC.png (1.45 KiB) Viewed 490 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.

This is already the future version that can be used with the DM42 once the new comparison functions, for example 0 <? "Loop",
work without memory leak (Free42 v. 3.0.3) ... so be patient!

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
approxPi[10^8]

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 { 98-Byte Prgm }
01▸LBL "PiMC"
02 0
03 SEED
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 RCL "Circle"
23 RCL÷ "Square"
24 4
25 ×
26 END
Attachments
PiMC.raw