Define a Random Experiment
In this step, we'll explore how to define a random experiment using Monte Carlo simulation in C. A random experiment is a process with uncertain outcomes that can be simulated using probability techniques.
Understanding Random Experiments
Let's create a simple C program to demonstrate a basic random experiment: coin flipping simulation.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_TRIALS 1000
int main() {
// Seed the random number generator
srand(time(NULL));
// Count of heads
int heads_count = 0;
// Simulate coin flips
for (int i = 0; i < NUM_TRIALS; i++) {
// Generate random number 0 or 1
int flip = rand() % 2;
// Count heads
if (flip == 0) {
heads_count++;
}
}
// Calculate probability of heads
double probability = (double)heads_count / NUM_TRIALS;
printf("Coin Flip Experiment:\n");
printf("Total Trials: %d\n", NUM_TRIALS);
printf("Heads Count: %d\n", heads_count);
printf("Estimated Probability of Heads: %.2f\n", probability);
return 0;
}
Example output:
Coin Flip Experiment:
Total Trials: 1000
Heads Count: 502
Estimated Probability of Heads: 0.50
Key Concepts Explained
-
Random Number Generation:
srand(time(NULL))
seeds the random number generator
rand() % 2
generates either 0 or 1 with equal probability
-
Experiment Design:
- We define a coin flip as our random experiment
- Run multiple trials (1000 in this case)
- Count the number of successful outcomes (heads)
-
Probability Estimation:
- Probability = (Number of Successful Outcomes) / (Total Number of Trials)
- In this case, we expect close to 0.5 probability for heads
Compile and Run the Program
## Create the source file
nano ~/project/coin_flip_experiment.c
## Compile the program
gcc ~/project/coin_flip_experiment.c -o ~/project/coin_flip_experiment
## Run the experiment
~/project/coin_flip_experiment
Example compilation and run output:
## Compilation
gcc ~/project/coin_flip_experiment.c -o ~/project/coin_flip_experiment
## Execution
~/project/coin_flip_experiment
Coin Flip Experiment:
Total Trials: 1000
Heads Count: 502
Estimated Probability of Heads: 0.50