E001: Calculating PI

Author

Hubert Baechli

Published

February 26, 2025

Programming exercise

In contrast to the simple method described below, the first exercise should calculates our own PI.

pi
[1] 3.141593

The following is a step-by-step guide to putting the first programming skills from the lesson into practice.

Basic idea

As Ven showed in the first lesson…

… if we throw thousands of random placed darts into a square field, the number of darts that fall into the enclosed circle should represent the area of that circle in relation to the area of the square.

In the following we will try to confirm this with our own programming skills.

1. Step

Generation of a random position for a single dart within a square. The square extends from -1 to +1 in the X-direction, as well as in the Y-direction.
Use a random number generator for a uniform distribution and save the result in the two variables x and y (GAP are placeholder)

x <- runif(n=GAP,min=GAP,max=GAP)
y <- GAP

2. Step

Now calculate the distance from this position to the center. You can use the following simplified formula for our chosen square

dist <- x**2 + y**2
print(dist)
[1] 0.8710378

3. Step

Create a decision rule and print “inside” if the point is inside the circle or “outside” if it is not.

if (dist <= GAP){
  GAP
} else {
  GAP
}

4. Step

Create now a loop (use for or while statement) and execute the code from steps 1 to 3 within it. You should get something like that now

Hint: Use may 10 iteration for the beginning

[1] "outside"
[1] "inside"
[1] "inside"
[1] "inside"
[1] "outside"
[1] "inside"
[1] "outside"
[1] "outside"
[1] "inside"
[1] "inside"

5. Step

Copy now the code from Step 4 and modify it in a way that instead of outputting a result for each point, it sums up the number of “insides”.

Use something like that,

n_insides <- 0
n_insides <- n_insides + 1
print(n_insides)
[1] 1

or more elegant write the results in a vector.

v_insides <- rep(x=0,10)
v_insides[2] <- 1
print(v_insides)
 [1] 0 1 0 0 0 0 0 0 0 0

If you use 1000 iteration you should became such a number

[1] 794

Final Step

As the final step, you now need to calculate PI from your result and compare it with the real one ;-)

print(selfmade_pi)
[1] 3.176
if (selfmade_pi == pi){
  print("YOU ARE UNBELIEFABLE")
} else {
  print("Try more iterations !!! (or try the function round)")
}
[1] "Try more iterations !!! (or try the function round)"