Skip to content
31 changes: 31 additions & 0 deletions contents/monte_carlo_integration/code/php/monte_carlo.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);

function in_circle(float $positionX, float $positionY, float $radius = 1): bool
{
return pow($positionX 2) + pow($positionY, 2) < pow($radius, 2);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing comma between $positionX and 2.

}

function random_zero_to_one(): float
{
return mt_rand() / mt_getrandmax();
}

function monte_carlo(int $samples, float $radius = 1): float
{
$inCircleCount = 0;

for ($i = 0; $i < $samples; $i++) {
if (in_circle(random_zero_to_one() * $radius, random_zero_to_one() * $radius, $radius))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taken from PSR-2:

The body of each structure MUST be enclosed by braces. This standardizes how
the structures look, and reduces the likelihood of introducing errors as new
lines get added to the body.

$inCircleCount++;
}

return 4 * $inCircleCount / $samples;
}

$piEstimate = monte_carlo(100000000);
$percentError = abs($piEstimate - pi()) / pi() * 100;

printf('The estimate of PI is: %s', $piEstimate);
echo PHP_EOL;
printf('The percent error is: %s', $percentError);
4 changes: 4 additions & 0 deletions contents/monte_carlo_integration/monte_carlo_integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ each point is tested to see whether it's in the circle or not:
[import:1-4, lang:"ruby"](code/ruby/monte_carlo.rb)
{% sample lang="f90" %}
[import:1-8, lang:"fortran"](code/fortran/monte_carlo.f90)
{% sample lang="php" %}
[import:4-7, lang:"php"](code/php/monte_carlo.php)
{% sample lang="lua" %}
[import:1-3, lang="lua"](code/lua/monte_carlo.lua)
{% sample lang="racket" %}
Expand Down Expand Up @@ -147,6 +149,8 @@ Feel free to submit your version via pull request, and thanks for reading!
[import, lang:"ruby"](code/ruby/monte_carlo.rb)
{% sample lang="f90" %}
[import, lang:"fortran"](code/fortran/monte_carlo.f90)
{% sample lang="php" %}
[import, lang:"php"](code/php/monte_carlo.php)
{% sample lang="lua" %}
[import, lang="lua"](code/lua/monte_carlo.lua)
{% sample lang="racket" %}
Expand Down