Created
August 2, 2017 19:25
-
-
Save dergachev/a75510a5d9d77d707a0dd73e3a433498 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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