-
-
Save whiler/048de88d1a2a50ade65171820b2f00e8 to your computer and use it in GitHub Desktop.
Concurrent π calculation with Golang!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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