Skip to content

Instantly share code, notes, and snippets.

@epi
Last active March 6, 2017 13:01
Show Gist options
  • Save epi/56b314515ebaa21084ea8a02ff9cba51 to your computer and use it in GitHub Desktop.
Save epi/56b314515ebaa21084ea8a02ff9cba51 to your computer and use it in GitHub Desktop.
Approximate Pi using randomly scattered points
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