Skip to content

Instantly share code, notes, and snippets.

@xreiju
Created May 7, 2017 02:36
Show Gist options
  • Save xreiju/1634f0814f1526212e5e56ad96b55583 to your computer and use it in GitHub Desktop.
Save xreiju/1634f0814f1526212e5e56ad96b55583 to your computer and use it in GitHub Desktop.
Calculate Pi with Monte Carlo Method in D
import std.stdio, std.random, std.math;
const POINT_AMOUNT = 1000;
struct Point {
real x, y;
bool isInCircle() {
real num = pow(x, 2) + pow(y, 2);
return num <= 1;
}
}
void main(string[] args) {
auto rnd = Random(unpredictableSeed);
int count = 0;
for(int i = 0; i < POINT_AMOUNT; i++) {
Point p = Point(uniform(0.0L, 1.0L, rnd), uniform(0.0L, 1.0L, rnd));
if(p.isInCircle()) count++;
writeln(4*cast(real)count/cast(real)i);
}
writeln("count:", count);
writeln("Pi:", 4*cast(real)count/cast(real)POINT_AMOUNT);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment