Skip to content

Commit c6ff7bb

Browse files
PudottaPomminButt4cak3
authored andcommitted
Added intergration of Monte Carlo for PHP (#431)
1 parent 19ba594 commit c6ff7bb

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
function in_circle(float $positionX, float $positionY, float $radius = 1): bool
5+
{
6+
return pow($positionX, 2) + pow($positionY, 2) < pow($radius, 2);
7+
}
8+
9+
function random_zero_to_one(): float
10+
{
11+
return mt_rand() / mt_getrandmax();
12+
}
13+
14+
function monte_carlo(int $samples, float $radius = 1): float
15+
{
16+
$inCircleCount = 0;
17+
18+
for ($i = 0; $i < $samples; $i++) {
19+
if (in_circle(random_zero_to_one() * $radius, random_zero_to_one() * $radius, $radius)) {
20+
$inCircleCount++;
21+
}
22+
}
23+
24+
return 4 * $inCircleCount / $samples;
25+
}
26+
27+
$piEstimate = monte_carlo(10000000);
28+
$percentError = abs($piEstimate - pi()) / pi() * 100;
29+
30+
printf('The estimate of PI is: %s', $piEstimate);
31+
echo PHP_EOL;
32+
printf('The percent error is: %s', $percentError);
33+
echo PHP_EOL;

contents/monte_carlo_integration/monte_carlo_integration.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ each point is tested to see whether it's in the circle or not:
7171
[import:1-4, lang:"ruby"](code/ruby/monte_carlo.rb)
7272
{% sample lang="f90" %}
7373
[import:1-8, lang:"fortran"](code/fortran/monte_carlo.f90)
74+
{% sample lang="php" %}
75+
[import:4-7, lang:"php"](code/php/monte_carlo.php)
7476
{% sample lang="lua" %}
7577
[import:1-3, lang="lua"](code/lua/monte_carlo.lua)
7678
{% sample lang="racket" %}
@@ -147,6 +149,8 @@ Feel free to submit your version via pull request, and thanks for reading!
147149
[import, lang:"ruby"](code/ruby/monte_carlo.rb)
148150
{% sample lang="f90" %}
149151
[import, lang:"fortran"](code/fortran/monte_carlo.f90)
152+
{% sample lang="php" %}
153+
[import, lang:"php"](code/php/monte_carlo.php)
150154
{% sample lang="lua" %}
151155
[import, lang="lua"](code/lua/monte_carlo.lua)
152156
{% sample lang="racket" %}

0 commit comments

Comments
 (0)