Skip to content

Added intergration of Monte Carlo for PHP #431

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Oct 7, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 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,33 @@
<?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);
}

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)) {
$inCircleCount++;
}
}

return 4 * $inCircleCount / $samples;
}

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

printf('The estimate of PI is: %s', $piEstimate);
echo PHP_EOL;
printf('The percent error is: %s', $percentError);
echo PHP_EOL;
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