Skip to content

Instantly share code, notes, and snippets.

@mandulaj
Created May 8, 2017 02:42
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 mandulaj/652a3fd7f0b288649282e4fa15d13228 to your computer and use it in GitHub Desktop.
Save mandulaj/652a3fd7f0b288649282e4fa15d13228 to your computer and use it in GitHub Desktop.
Coin
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"os"
)
const (
FLIPS = 1e6
)
type FlipArray struct {
Flips []int
}
func flip() bool {
return rand.Intn(2) == 0
}
func average(array []int) float64 {
sum := float64(0)
for _, value := range array {
sum += float64(value)
}
return float64(sum) / float64(len(array))
}
func main() {
flipsT := make([]int, 0, FLIPS)
flips := 0
heads := 0
for i := 0; i < FLIPS; i++ {
for heads < 10 {
if flip() {
heads++
} else {
heads = 0
}
flips++
}
flipsT = append(flipsT, flips)
flips = 0
heads = 0
if i%1000 == 0 {
fmt.Println(i)
}
}
fmt.Println()
fmt.Println(average(flipsT))
f := FlipArray{flipsT}
b, err := json.Marshal(f)
if err != nil {
panic(err)
}
err = ioutil.WriteFile("output.json", b, os.ModePerm)
if err != nil {
panic(err)
}
}
package main
import (
"fmt"
"math/rand"
"time"
)
const (
FLIPS = 1e6
CORES = 5
)
func flip() bool {
return rand.Intn(2) == 0
}
func get10() int {
heads := 0
flips := 0
for heads < 10 {
if flip() {
heads++
} else {
heads = 0
}
flips++
}
return flips
}
func runBatch(n int, c chan int) {
for i := 0; i < n; i++ {
c <- get10()
}
}
func average(array []int) float64 {
sum := 0
for _, value := range array {
sum += value
}
return float64(sum) / float64(len(array))
}
func main() {
flipsT := make([]int, 0, FLIPS)
results := make(chan int, 1000)
batchSize := FLIPS / CORES
for i := 0; i < CORES; i++ {
go runBatch(batchSize, results)
}
i := 0
for {
i++
if i%1000 == 0 {
fmt.Println(i)
}
select {
case result := <-results:
flipsT = append(flipsT, result)
case <-time.After(time.Second):
break
}
}
fmt.Println()
fmt.Println(average(flipsT))
}
package main
import "encoding/binary"
import "crypto/rand"
func main() {
var n int32
binary.Read(rand.Reader, binary.LittleEndian, &n)
println(n)
}
import numpy as np
import matplotlib.pyplot as plt
import json
with open("output.json", "r") as f:
read_data = f.read()
data = np.array(json.loads(read_data)["Flips"], dtype="int32")
print data
data = data[~(data > 15000)]
print np.max(data)
print np.min(data)
print np.mean(data)
y = np.bincount(data)
ii = np.nonzero(y)
print y
print ii
ii = ii[0]
print ii
op = np.vstack((ii, y[ii]))
x = op[0]
y = np.log(op[1])
fit = np.polyfit(x,y,1)
print fit
print str(np.e**fit[1]) + "e^(" + str(fit[0]) + "x)"
fit_fn = np.poly1d(fit)
plt.plot(x,y, 'yo', x, fit_fn(x), '--k')
# n, bins, patches = plt.hist(data, 100, normed=1, facecolor="green")
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment