Monte Carlo Simulation
Monte Carlo Simulation
prediction and modeling problems. Here's a simple program in Turbo C++ to demonstrate the Monte
Carlo simulation for estimating the value of π. This program randomly generates points in a unit
square and determines how many fall inside the quarter circle to estimate π.
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
int main() {
int n;
int insideCircle = 0;
double x, y;
cout << "Enter the number of points for the simulation: ";
cin >> n;
srand(time(0));
x = static_cast<double>(rand()) / RAND_MAX;
y = static_cast<double>(rand()) / RAND_MAX;
if (x * x + y * y <= 1.0) {
insideCircle++;
cout << "Estimated value of pi: " << piEstimate << endl;
return 0;
```
### Explanation:
1. **Variables**:
- `insideCircle`: Counter for points that fall inside the quarter circle.
2. **Input**:
- Prompts the user to enter the number of points for the simulation.
- Uses `srand(time(0))` to seed the random number generator with the current time to ensure
different results for each run.
- `rand()` generates random numbers. Dividing by `RAND_MAX` normalizes them to the range [0,
1].
- Check if the point is inside the quarter circle (`x^2 + y^2 <= 1`).
- The ratio of points inside the quarter circle to the total number of points, multiplied by 4,
estimates the value of π.
This program demonstrates the basic concept of Monte Carlo simulation by estimating the value of
π. The more points you generate, the more accurate the estimation becomes.
Here's a Turbo C++ program for Monte Carlo simulation, rewritten without using namespaces. This
example approximates the value of π using Monte Carlo methods.
```cpp
#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
int insideCircle = 0;
if (x * x + y * y <= 1) {
insideCircle++;
// Calculate Pi
int main() {
int numPoints;
srand((unsigned)time(NULL));
cout << "Enter the number of points for the Monte Carlo simulation: ";
cout << "Estimated value of Pi is: " << piEstimate << endl;
return 0;
```
### Explanation:
- Generates random points `(x, y)` within the unit square `[0, 1] x [0, 1]`.
- Checks if the point falls within the unit circle centered at the origin by evaluating if `x^2 + y^2 <=
1`.
- Counts the number of points inside the circle and estimates π as `(4.0 * insideCircle) / numPoints`.
2. **Main Function**:
- Seeds the random number generator with the current time using `srand((unsigned)time(NULL))`.
### Notes:
- **Random Number Generation**: Uses `rand()` to generate random numbers and `srand()` to seed
the random number generator.
- **Floating-Point Arithmetic**: The division and arithmetic operations are performed using `double`
to ensure precision.
This program is compatible with Turbo C++ and provides an approximation of π using Monte Carlo
simulation. Adjust the number of points for better accuracy as needed.