Advertisement
Guest User

Untitled

a guest
Mar 28th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 1.15 KB | None | 0 0
  1. import 'dart:async';
  2. import 'dart:math' show Random;
  3.  
  4. main() async {
  5.   print('Compute π using the Monte Carlo method.');
  6.   await for (var estimate in computePi()) {
  7.     print('π ≅ $estimate');
  8.   }
  9. }
  10.  
  11. /// Generates a stream of increasingly accurate estimates of π.
  12. Stream<double> computePi({int batch: 1000000}) async* {
  13.   var total = 0;
  14.   var count = 0;
  15.   while (true) {
  16.     var points = generateRandom().take(batch);
  17.     var inside = points.where((p) => p.isInsideUnitCircle);
  18.     total += batch;
  19.     count += inside.length;
  20.     var ratio = count / total;
  21.     // Area of a circle is A = π⋅r², therefore π = A/r².
  22.     // So, when given random points with x ∈ <0,1>,
  23.     // y ∈ <0,1>, the ratio of those inside a unit circle
  24.     // should approach π / 4. Therefore, the value of π
  25.     // should be:
  26.     yield ratio * 4;
  27.   }
  28. }
  29.  
  30. Iterable<Point> generateRandom([int seed]) sync* {
  31.   final random = new Random(seed);
  32.   while (true) {
  33.     yield new Point(random.nextDouble(), random.nextDouble());
  34.   }
  35. }
  36.  
  37. class Point {
  38.   final double x, y;
  39.   const Point(this.x, this.y);
  40.   bool get isInsideUnitCircle => x * x + y * y <= 1;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement