{{ message }}

Instantly share code, notes, and snippets.

# dergachev/pi.php

Created Aug 2, 2017
This file contains 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
 Finding Pi
"; echo "We will use a circle with radius 1, inside a 2x2 square to calculate Pi.
We will pick random points in the square and see if they also land in the circle.
Then we will calcuate the ratio and multiply by 4 to estimate Pi.

"; // 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 . "
"; echo "In the square: " . \$insquare . "
"; echo "Ratio: " . \$incircle/\$insquare . "
"; echo "Our Pi estimate is " . \$incircle*4/\$insquare; ?>