pi.go 598 B

12345678910111213141516171819202122232425262728293031323334
  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. import (
  9. "fmt"
  10. "math"
  11. )
  12. func main() {
  13. fmt.Println(pi(5000))
  14. }
  15. // pi launches n goroutines to compute an
  16. // approximation of pi.
  17. func pi(n int) float64 {
  18. ch := make(chan float64)
  19. for k := 0; k <= n; k++ {
  20. go term(ch, float64(k))
  21. }
  22. f := 0.0
  23. for k := 0; k <= n; k++ {
  24. f += <-ch
  25. }
  26. return f
  27. }
  28. func term(ch chan float64, k float64) {
  29. ch <- 4 * math.Pow(-1, k) / (2*k + 1)
  30. }