Calculate the Value of Pi with Monte Carlo Method in PHP – A Step-by-Step Guide

The Monte Carlo method works by generating random points within a square and counting the number of points that fall inside a circle inscribed within the square. The ratio of the number of points inside the circle to the total number of points generated is proportional to the ratio of the area of the circle to the area of the square. By multiplying this ratio by 4, we can estimate the value of π.

<?php

// The Monte Carlo method is a statistical method that uses random sampling to obtain numerical results.
// One of the most famous applications of this method is to calculate the value of π.

// Define the number of iterations for the simulation
$iterations = 1000000;

// Initialize the count of points inside the circle
$pointsInside = 0;

// Loop through the number of iterations
for ($i = 0; $i < $iterations; $i++) {
    // Generate random x and y values between -1 and 1
    $x = rand(-1000000, 1000000) / 1000000;
    $y = rand(-1000000, 1000000) / 1000000;
    
    // Check if the point is inside the circle
    if ($x * $x + $y * $y <= 1) {
        $pointsInside++;
    }
}

// Calculate the value of π using the Monte Carlo method
$pi = 4 * ($pointsInside / $iterations);

// Output the result
echo "The estimated value of pi is: " . $pi;

 

 

In this code, we generate $iterations number of random x and y values between -1 and 1, and check if each point is inside the circle using the equation $x * $x + $y * $y <= 1. If the point is inside the circle, we increment the $pointsInside count. Finally, we calculate the estimated value of π by multiplying the ratio of `$pointsInside` to $iterations by 4 and output the result.

Note that: the more iterations we run, the more accurate the result will be, but it will also take longer to run.

Leave A Comment

Your email address will not be published. Required fields are marked *