Skip to content

Instantly share code, notes, and snippets.

@wbailey
Created May 30, 2013 17:22
Show Gist options
  • Save wbailey/5679595 to your computer and use it in GitHub Desktop.
Save wbailey/5679595 to your computer and use it in GitHub Desktop.
Statistical method for determine the value of Pi in Ruby and Go
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
var pi, dev float64
func stones(N int) (float64, float64) {
var x, y, point, Nc, Ns, sum, mu, V float64
for i := 0; i < N; i++ {
x = 2.0 * rand.Float64() - 1.0
y = 2.0 * rand.Float64() - 1.0
point = x * x + y * y
if point < 1.0 {
Nc += 1
} else {
Ns += 1
}
}
pi = 4.0 * Nc / (Nc + Ns)
sum += pi
mu = sum/(Nc + Ns)
V = (math.Pow( (mu - pi), 2))/(Nc + Ns)
dev = math.Pow(V, 0.5)
return pi, dev
}
func main() {
var count int
rand.Seed(time.Now().UTC().UnixNano())
for i := 1; i <= 100; i += 1 {
count = i * 1000
pi, dev = stones(count)
fmt.Printf("%d\t%f10\t%f10\n", count, pi, dev)
}
}
def stones iterations
r = Random.new(Time.now.utc.usec)
nc = 0.0
iterations.times do
x = 2.0 * r.rand - 1.0
y = 2.0 * r.rand - 1.0
point = x * x + y * y
nc += 1 if point < 1.0
end
pi = 4.0 * nc / iterations
mu = pi / iterations
sigma = ((pi - mu) ** 2) / iterations
dev = sigma ** 0.5
return pi, dev
end
101.times do |i|
count = i * 1000
pi, dev = stones(count)
printf("%d\t%f10\t%f10\n", count, pi, dev)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment