Print the Probability
In this final step, you'll enhance the Poisson probability calculation program by adding more detailed probability printing and formatting.
Open the previous file to modify the code:
cd ~/project
nano poisson_prob.c
Update the code to improve probability presentation:
#include <stdio.h>
#include <math.h>
// Function to calculate factorial
double factorial(int n) {
if (n <= 1) return 1;
double result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
// Calculate Poisson probability
double poisson_probability(double lambda, int k) {
double numerator = pow(lambda, k) * exp(-lambda);
double denominator = factorial(k);
return numerator / denominator;
}
int main() {
double lambda;
int k;
printf("Poisson Probability Calculator\n");
printf("------------------------------\n");
printf("Enter lambda (average number of events): ");
scanf("%lf", &lambda);
printf("Enter k (number of occurrences): ");
scanf("%d", &k);
double probability = poisson_probability(lambda, k);
printf("\nCalculation Results:\n");
printf("Lambda (λ): %.2f\n", lambda);
printf("k: %d\n", k);
printf("Probability P(X = %d): %.4f\n", k, probability);
printf("Percentage: %.2f%%\n", probability * 100);
return 0;
}
Compile the program:
gcc -o poisson_prob poisson_prob.c -lm
Example output:
Poisson Probability Calculator
------------------------------
Enter lambda (average number of events): 3.5
Enter k (number of occurrences): 2
Calculation Results:
Lambda (λ): 3.50
k: 2
Probability P(X = 2): 0.1674
Percentage: 16.74%
Key improvements:
- Added a title for the calculator
- Included percentage representation
- Improved output formatting
- More descriptive output sections
Run the program:
./poisson_prob