Skip to content

Instantly share code, notes, and snippets.

@yaraki
Created January 21, 2014 12:22
Show Gist options
  • Save yaraki/8539047 to your computer and use it in GitHub Desktop.
Save yaraki/8539047 to your computer and use it in GitHub Desktop.
Ramanujan's formulas of pi in Go
package main
import (
"fmt"
"math"
)
func fact(n float64) float64 {
r := float64(1)
for 1 < n {
r *= n
n -= 1
}
return r
}
func pi1(max float64) float64 {
modifier := 2 * math.Sqrt(2) / math.Pow(99, 2)
sigma := float64(0)
for n := float64(0); n <= max; n += 1 {
numerator := fact(4 * n) * (1103 + 26490 * n)
denominator := math.Pow(math.Pow(4, n) * math.Pow(99, n) * fact(n), 4)
sigma += numerator / denominator
}
return 1 / (modifier * sigma)
}
func pi2(max float64) float64 {
sigma := float64(0)
for n := float64(0); n <= max; n += 1 {
numerator := math.Pow(-1, n) * fact(4 * n) * (1123 + 21460 * n)
denominator := math.Pow(882, 2 * n + 1) * math.Pow(math.Pow(4, n) * fact(n), 4)
sigma += numerator / denominator
}
return 4 / sigma
}
func main() {
fmt.Println(pi1(41))
fmt.Println(pi2(41))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment