Last active
February 25, 2021 14:07
-
-
Save drupol/0c759613fc78496dbfe509a43493df8c to your computer and use it in GitHub Desktop.
Find Pi using Wallis formula
This file contains hidden or 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
| <?php | |
| /** | |
| * Wallis formula | |
| * | |
| * 2 2 4 4 6 6 8 8 | |
| * pi = 2 x --- x --- x --- x --- x --- x --- x --- x --- x ... | |
| * 1 3 3 5 5 7 7 9 | |
| */ | |
| declare(strict_types=1); | |
| namespace App; | |
| include __DIR__ . '/../vendor/autoload.php'; | |
| use Generator; | |
| use loophp\collection\Collection; | |
| $precision = 10 ** -7; | |
| $pi = Collection::unfold(static fn (int $n = 0): int => $n + 1) | |
| ->map( | |
| static fn (int $i): int => $i * 2, | |
| static fn (int $i): array => [$i, $i], | |
| static fn (array $chunk): array => [$chunk[0] / ($chunk[0] - 1), $chunk[1] / ($chunk[1] + 1)] | |
| ) | |
| ->unwrap() | |
| ->reduction( | |
| static fn (float $carry, float $i): float => $carry * $i, | |
| 2 | |
| ) | |
| ->window(1) | |
| ->drop(1) | |
| ->until( // Expliquer que x(n+1) - x(n) tend vers 0 ... voirs cours math elem Troestler | |
| static fn (array $v): bool => abs($v[0] - $v[1]) < ($precision / 2) | |
| ) | |
| ->unwindow() | |
| ->normalize() | |
| ->last(); | |
| dump($pi->current()); // 3.1415926035884 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment