-
-
Notifications
You must be signed in to change notification settings - Fork 359
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
Changes from 9 commits
4bc5868
b411169
559c7fc
95eafaf
a7a3738
afa9d6d
ed52163
ec2f420
e3409c6
4a241aa
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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 | ||
Butt4cak3 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
return pow($positionX 2) + pow($positionY, 2) < pow($radius, 2); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Missing comma between |
||
} | ||
|
||
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)) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Taken from PSR-2:
|
||
$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); |
Uh oh!
There was an error while loading. Please reload this page.