1
0

sample.dart.txt 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import 'dart:async';
  2. import 'dart:math' show Random;
  3. main() async {
  4. print('Compute π using the Monte Carlo method.');
  5. await for (var estimate in computePi().take(100)) {
  6. print('π ≅ $estimate');
  7. }
  8. }
  9. /// Generates a stream of increasingly accurate estimates of π.
  10. Stream<double> computePi({int batch: 100000}) async* {
  11. var total = 0;
  12. var count = 0;
  13. while (true) {
  14. var points = generateRandom().take(batch);
  15. var inside = points.where((p) => p.isInsideUnitCircle);
  16. total += batch;
  17. count += inside.length;
  18. var ratio = count / total;
  19. // Area of a circle is A = π⋅r², therefore π = A/r².
  20. // So, when given random points with x ∈ <0,1>,
  21. // y ∈ <0,1>, the ratio of those inside a unit circle
  22. // should approach π / 4. Therefore, the value of π
  23. // should be:
  24. yield ratio * 4;
  25. }
  26. }
  27. Iterable<Point> generateRandom([int seed]) sync* {
  28. final random = Random(seed);
  29. while (true) {
  30. yield Point(random.nextDouble(), random.nextDouble());
  31. }
  32. }
  33. class Point {
  34. final double x, y;
  35. const Point(this.x, this.y);
  36. bool get isInsideUnitCircle => x * x + y * y <= 1;
  37. }