Home | History | Annotate | Download | only in play
      1 // Concurrent computation of pi.
      2 // See https://goo.gl/la6Kli.
      3 //
      4 // This demonstrates Go's ability to handle
      5 // large numbers of concurrent processes.
      6 // It is an unreasonable way to calculate pi.
      7 package main
      8 
      9 import (
     10 	"fmt"
     11 	"math"
     12 )
     13 
     14 func main() {
     15 	fmt.Println(pi(5000))
     16 }
     17 
     18 // pi launches n goroutines to compute an
     19 // approximation of pi.
     20 func pi(n int) float64 {
     21 	ch := make(chan float64)
     22 	for k := 0; k <= n; k++ {
     23 		go term(ch, float64(k))
     24 	}
     25 	f := 0.0
     26 	for k := 0; k <= n; k++ {
     27 		f += <-ch
     28 	}
     29 	return f
     30 }
     31 
     32 func term(ch chan float64, k float64) {
     33 	ch <- 4 * math.Pow(-1, k) / (2*k + 1)
     34 }
     35