Skip to content

Instantly share code, notes, and snippets.

@dergachev
Created Aug 2, 2017
Embed
What would you like to do?
<!DOCTYPE html>
<html>
<head>
<link type='text/css' rel='stylesheet' href='style.css'/>
<title>Finding Pi</title>
</head>
<body>
<?php
echo "Here is PHP, echoing Pi:" . " " . M_PI . "<br /><br />";
echo "We will use a circle with radius 1, inside a 2x2 square to calculate Pi. <br />
We will pick random points in the square and see if they also land in the circle. <br />
Then we will calcuate the ratio and multiply by 4 to estimate Pi.<br /><br />";
// Arrays to hold counts for when a point is in or out of the circle.
// the square array really just counts how many iterations we do.
$incircle = 0;
$insquare = 0;
// for loop iterates as many times as we like. The higher the iteration, the more accurate the end result.
for ($i = 0; $i<=10000000; $i++){
// x co-ordinate generator
$xgen = (mt_rand()*2) / mt_getrandmax();
$x = $xgen-1;
// y co-ordinate generator
$ygen = (mt_rand()*2) / mt_getrandmax();
$y = $ygen-1;
// if statement determines whether the point is in or out of the circle.
if (sqrt($x*$x + $y*$y) <= 1) {
$incircle++;
}
$insquare++;
}
echo "In the circle: " . $incircle . "<br />";
echo "In the square: " . $insquare . "<br />";
echo "Ratio: " . $incircle/$insquare . "<br />";
echo "Our Pi estimate is " . $incircle*4/$insquare;
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment