Created
October 8, 2016 18:37
-
-
Save tk3369/0343021451aaf9b68d820f74b6404689 to your computer and use it in GitHub Desktop.
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
// Estimate PI using monte carlo simulation | |
// See http://www.davidrobles.net/blog/2014/06/22/estimating-pi-using-monte-carlo-simulations/ | |
import 'dart:math'; | |
Random rnd = new Random(); | |
// Return a random point within [-1, 1] coordinate plane | |
class UnitPoint { | |
double x; | |
double y; | |
UnitPoint() { | |
this.x = rnd.nextDouble() * (rnd.nextInt(2) == 0 ? -1 : 1); | |
this.y = rnd.nextDouble() * (rnd.nextInt(2) == 0 ? -1 : 1); | |
} | |
String toString() { | |
return "x: ${x.toStringAsFixed(2)} y: ${y.toStringAsFixed(2)}"; | |
} | |
} | |
void main() { | |
int N = 100000000; | |
var inCircle = (UnitPoint p) => (p.x*p.x + p.y*p.y) < 1.0; | |
print("Started: ${new DateTime.now()}"); | |
int C = 0; | |
for (int i = 0; i < N; i++) { | |
if (inCircle(new UnitPoint())) { | |
C++; | |
} | |
} | |
print("N = ${N}"); | |
print("C = ${C}"); | |
print("estimated pi value = ${(4 * C / N).toStringAsFixed(5)}"); | |
print("Ended: ${new DateTime.now()}"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment