Estimate PI using monte carlo simulation
Find this at dartpad.dartlang.org/?source=9c828f5e-8783-4865-afad-b0fec225366b.
Created with <3 with dartpad.dartlang.org.
Estimate PI using monte carlo simulation
Find this at dartpad.dartlang.org/?source=9c828f5e-8783-4865-afad-b0fec225366b.
Created with <3 with dartpad.dartlang.org.
| // 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()}"); | |
| } |