Skip to content

Instantly share code, notes, and snippets.

@campoy
Last active March 13, 2017 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save campoy/da3ecaacea2a03f43815a54200fe2339 to your computer and use it in GitHub Desktop.
Save campoy/da3ecaacea2a03f43815a54200fe2339 to your computer and use it in GitHub Desktop.
Computing pi one gcd at a time! Inspired by https://www.youtube.com/watch?v=RZBhSi_PwHU&t=891s
package main
import (
"fmt"
"math"
"math/rand"
"runtime"
"sync"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
var coprimes, total int64
var mu sync.Mutex
for i := 0; i < 2*runtime.NumCPU(); i++ {
go func() {
for {
a, b := rand.Uint64(), rand.Uint64()
g := gcd(a, b)
mu.Lock()
total++
if g == 1 {
coprimes++
}
mu.Unlock()
}
}()
}
for range time.Tick(time.Second) {
mu.Lock()
x := float64(coprimes) / float64(total)
pi := math.Sqrt(6 / x)
fmt.Printf("%g\t%10d\t%g\n", pi, total, 100*math.Abs(1-pi/math.Pi))
mu.Unlock()
}
}
func gcd(a, b uint64) uint64 {
for b != 0 {
a, b = b, a%b
}
return a
}
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
var coprimes int64
for total := 1; true; total++ {
if gcd(rand.Uint64(), rand.Uint64()) == 1 {
coprimes++
}
if total%1000000 == 0 {
x := float64(coprimes) / float64(total)
pi := math.Sqrt(6 / x)
fmt.Printf("%g\t%10d\t%g\n", pi, total, 100*math.Abs(1-pi/math.Pi))
}
}
}
func gcd(a, b uint64) uint64 {
for b != 0 {
a, b = b, a%b
}
return a
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment