pi[1] 3.141593Hubert Baechli
February 26, 2025
In contrast to the simple method described below, the first exercise should calculates our own PI.
The following is a step-by-step guide to putting the first programming skills from the lesson into practice.
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.
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)
Now calculate the distance from this position to the center. You can use the following simplified formula for our chosen square
Create a decision rule and print “inside” if the point is inside the circle or “outside” if it is not.
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"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,
or more elegant write the results in a vector.
If you use 1000 iteration you should became such a number
[1] 794As the final step, you now need to calculate PI from your result and compare it with the real one ;-)