Last active
March 13, 2017 18:10
-
-
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
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" | |
"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 | |
} |
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" | |
"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