-
-
Save epi/56b314515ebaa21084ea8a02ff9cba51 to your computer and use it in GitHub Desktop.
Approximate Pi using randomly scattered points
This file contains 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
auto approximate(double radius, uint npoints) | |
{ | |
import std.range : generate, take; | |
import std.algorithm : count; | |
import std.random : Xorshift, unpredictableSeed, uniform; | |
auto radius2 = radius * radius; | |
auto generator = Xorshift(unpredictableSeed); | |
auto makeRandomCoord() { return uniform!`[]`(0, radius, generator) ^^ 2; } | |
return generate(() => makeRandomCoord() + makeRandomCoord()) | |
.take(npoints) | |
.count!(r => r <= radius2) | |
* 4.0 / npoints; | |
} | |
void main() | |
{ | |
import std.range : iota; | |
import std.algorithm : map; | |
import std.stdio : writefln; | |
import std.math : abs; | |
enum pi = 3.14159265359; | |
foreach (radius; iota(0, 10).map!(n => 10 ^^ n)) { | |
writefln("%(%15s%)", | |
iota(0, 8).map!(m => abs(approximate(radius, 10 ^^ m) - pi))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment