AGH Computer Science C Programming Laboratory 5
AGH Computer Science C Programming Laboratory 5
2024
1. [6points] Monte Carlo methods are a broad class of computational algorithms that rely on
repeated random sampling to obtain numerical results. One of the basic examples of getting started
with the Monte Carlo algorithm is the estimation of Pi.
Estimation of Pi
The idea is to simulate random (x, y) points in a 2D plane with domain as a square of side 1 unit.
Imagine a circle inside the same domain with same diameter and inscribed into the square. We then
calculate the ratio of number points that lied inside the circle and total number of generated points.
The algorithm:
a) Initialize a variable that counts the number of points inside the circle.
b) In the loop:
c) Generate a pseudo-random x coordinate between -1 and 1.
d) Generate a pseudo-random y coordinate between -1 and 1.
e) Check if the drawn point lies inside the circle with a radius of 1.
f) If so, increase the appropriate variable.
g) Repeat the calculation in loop 7000.
h) Calculate and print out your estimate for pi.
Test data:
2. [3points] Let's see how the estimate value depends on the number of pseudo-random number
generations. Add a loop to the previous program that will control the number of pseudo-random
number generations.
Test data:
3. [6 points] Numerical integration comprises a broad family of algorithms for calculating the
numerical value of a definite integral. The basic problem in numerical integration is to compute an
𝑏
approximate solution to a definite integral ∫𝑎 ⬚ 𝑓(𝑥)𝑑𝑥to a given degree of accuracy. Rectangular
integration (a.k.a. The Midpoint Rule) is a numerical integration technique that approximates the
integral of a function with a rectangle. It uses rectangles to approximate the area under the curve.
𝐴4
Now just use a loop to calculate the sum of all rectangles to calculate the numerical approximation
of the definite integral.
We will calculate the integrals of the following functions. Insert the following code into the
program, above the main function.
a) In the main function, create two variables that will be the beginning and end of the integration
interval.
b) Create a variable that will hold the number of rectangles.
c) Create a variable that is equal to the base of the rectangles. Calculate its value using previously
defined variables.
d) Create a variable that will hold the result of the integral calculation.
Test data:
4. [5 points] Let's check how the value of the definite integral depends on the number of rectangles.
Add a loop to the previous program that will control the number of rectangles. Here's a function that
we're going to integrate in the range 0 to 1.
Next time:
Laboratory 06 – Arrays