summaryrefslogtreecommitdiff
path: root/doc/play/pi.go
diff options
context:
space:
mode:
authorOndřej Surý <ondrej@sury.org>2012-04-06 15:14:11 +0200
committerOndřej Surý <ondrej@sury.org>2012-04-06 15:14:11 +0200
commit505c19580e0f43fe5224431459cacb7c21edd93d (patch)
tree79e2634c253d60afc0cc0b2f510dc7dcbb48497b /doc/play/pi.go
parent1336a7c91e596c423a49d1194ea42d98bca0d958 (diff)
downloadgolang-505c19580e0f43fe5224431459cacb7c21edd93d.tar.gz
Imported Upstream version 1upstream/1
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)
+}