Friday, September 29, 2023

Calculation of π Using the Monte Carlo Method

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

// Function to generate a random number between 0 and 1
double RandomNumber() {double r=RAND_MAX;
return rand() / r;
}

// Function to estimate π using the Monte Carlo method
double estimatePi(int totalPoints) {
int insideCircle = 0; // Number of points inside the quarter-circle
for (int i = 0; i < totalPoints; ++i) {
double x = RandomNumber(); // Generate random x-coordinate between 0 and 1
double y = RandomNumber(); // Generate random y-coordinate between 0 and 1
// Check if the point (x, y) is inside the quarter-circle (x² + y² <= 1)
if (x * x + y * y <= 1) {
insideCircle++;
}
}
// Estimate π using Monte Carlo method: π/4 ≈ (Number of points inside circle) / (Total number of points)
return 4.0 * static_cast<double>(insideCircle) / totalPoints;
}

int main() {
srand(time(0)); // Seed the random number generator with the current time
int totalPoints = 1000000; // Total number of random points to generate
double estimatedPi = estimatePi(totalPoints);
cout << "Estimated value of π: " << estimatedPi << endl;
return 0;
}



In this program:
We use the random number generator to generate random points in the unit square [0, 1] × [0, 1].
We count the number of points that fall inside the quarter-circle (x^2 + y^2 ≤ 1) by checking if the point satisfies this condition.
Finally, we estimate the value of π using the formula: π/4 ≈ (Number of points inside circle) / (Total number of points).

Compile and run this program, and it will provide an estimated value of π using the Monte Carlo method. The more points you generate (totalPoints), the more accurate the estimate will be. 

The logic for estimating π is encapsulated within the
estimatePi function. The estimatePi function takes the total number of random points as a parameter and returns the estimated value of π. This separation of concerns makes the code more modular and easier to maintain.

No comments:

Post a Comment

N-point Star in Microsoft Visual Studio Console App

#include <windows.h> #include <cmath> #include <iostream> LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam,...