Skip to content

Instantly share code, notes, and snippets.

@whiler
Forked from taiypeo/pi.go
Last active February 18, 2023 01:11
Show Gist options
  • Save whiler/048de88d1a2a50ade65171820b2f00e8 to your computer and use it in GitHub Desktop.
Save whiler/048de88d1a2a50ade65171820b2f00e8 to your computer and use it in GitHub Desktop.
Concurrent π calculation with Golang!
package main
import (
"fmt"
"math"
"runtime"
"time"
)
// Using the Bailey–Borwein–Plouffe formula
func partialSum(ch chan<- float64, offset, workers, amount int) {
var i, sum float64 = 0.0, 0.0
for i = float64(offset); i < float64(offset+workers*amount); i += float64(workers) {
sum += 1 / math.Pow(16, i) * (4/(8*i+1) - 2/(8*i+4) - 1/(8*i+5) - 1/(8*i+6))
}
ch <- sum
}
func main() {
var (
pi = 0.0
workers = runtime.NumCPU()
amount = 1_0000_0000
ch = make(chan float64, workers)
start time.Time
duration time.Duration
i int
)
defer close(ch)
start = time.Now()
for i = 0; i < workers; i++ {
go partialSum(ch, i, workers, amount)
}
for i = 0; i < workers; i++ {
pi += <-ch
}
duration = time.Since(start)
fmt.Println("Calculated π:", pi)
fmt.Println("Duration: ", duration)
fmt.Println("Difference between math.Pi and calculated:", pi-math.Pi)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment