summaryrefslogtreecommitdiff
path: root/doc/play/pi.go
diff options
context:
space:
mode:
authorOndřej Surý <ondrej@sury.org>2012-03-26 16:50:58 +0200
committerOndřej Surý <ondrej@sury.org>2012-03-26 16:50:58 +0200
commit519725bb3c075ee2462c929f5997cb068e18466a (patch)
tree5b162e8488ad147a645048c073577821b4a2bee9 /doc/play/pi.go
parent842623c5dd2819d980ca9c58048d6bc6ed82475f (diff)
downloadgolang-upstream-weekly/2012.03.22.tar.gz
Imported Upstream version 2012.03.22upstream-weekly/2012.03.22
Diffstat (limited to 'doc/play/pi.go')
-rw-r--r--doc/play/pi.go34
1 files changed, 34 insertions, 0 deletions
diff --git a/doc/play/pi.go b/doc/play/pi.go
new file mode 100644
index 000000000..f2f5dca74
--- /dev/null
+++ b/doc/play/pi.go
@@ -0,0 +1,34 @@
+// Concurrent computation of pi.
+// See http://goo.gl/ZuTZM.
+//
+// This demonstrates Go's ability to handle
+// large numbers of concurrent processes.
+// It is an unreasonable way to calculate pi.
+package main
+
+import (
+ "fmt"
+ "math"
+)
+
+func main() {
+ fmt.Println(pi(5000))
+}
+
+// pi launches n goroutines to compute an
+// approximation of pi.
+func pi(n int) float64 {
+ ch := make(chan float64)
+ for k := 0; k <= n; k++ {
+ go term(ch, float64(k))
+ }
+ f := 0.0
+ for k := 0; k <= n; k++ {
+ f += <-ch
+ }
+ return f
+}
+
+func term(ch chan float64, k float64) {
+ ch <- 4 * math.Pow(-1, k) / (2*k + 1)
+}