From 0ccda7ac4de1a89d8a04b11c5b5a4be4e648f7e2 Mon Sep 17 00:00:00 2001 From: Jonathan Date: Tue, 7 Jun 2022 14:21:13 +0200 Subject: [PATCH] Format code --- website/index/samples/sample.dart.txt | 28 +++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/website/index/samples/sample.dart.txt b/website/index/samples/sample.dart.txt index 3a16aa6d..c9eb663e 100644 --- a/website/index/samples/sample.dart.txt +++ b/website/index/samples/sample.dart.txt @@ -1,21 +1,24 @@ -import 'dart:async'; import 'dart:math' show Random; -main() async { + +void main() async { print('Compute π using the Monte Carlo method.'); - await for (var estimate in computePi().take(100)) { + await for (final estimate in computePi().take(100)) { print('π ≅ $estimate'); } } + /// Generates a stream of increasingly accurate estimates of π. -Stream computePi({int batch: 100000}) async* { - var total = 0; +Stream computePi({int batch = 100000}) async* { + var total = 0; // Inferred to be of type int var count = 0; while (true) { - var points = generateRandom().take(batch); - var inside = points.where((p) => p.isInsideUnitCircle); + final points = generateRandom().take(batch); + final inside = points.where((p) => p.isInsideUnitCircle); + total += batch; count += inside.length; - var ratio = count / total; + final ratio = count / total; + // Area of a circle is A = π⋅r², therefore π = A/r². // So, when given random points with x ∈ <0,1>, // y ∈ <0,1>, the ratio of those inside a unit circle @@ -24,14 +27,19 @@ Stream computePi({int batch: 100000}) async* { yield ratio * 4; } } -Iterable generateRandom([int seed]) sync* { + +Iterable generateRandom([int? seed]) sync* { final random = Random(seed); while (true) { yield Point(random.nextDouble(), random.nextDouble()); } } + class Point { - final double x, y; + final double x; + final double y; + const Point(this.x, this.y); + bool get isInsideUnitCircle => x * x + y * y <= 1; }