Last active
March 11, 2016 18:41
-
-
Save pgburt/39c931b979cbb38d8c56 to your computer and use it in GitHub Desktop.
pi-reduce
This file contains hidden or 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 ( | |
"encoding/json" | |
"fmt" | |
"github.com/iron-io/iron_go/worker" | |
"github.com/iron-io/iron_go3/mq" | |
"math/big" | |
"time" | |
) | |
type PiChunks struct { | |
Begin int | |
End int | |
Result string | |
} | |
type Payload struct { | |
Num_of_1k_runs int | |
} | |
func GetMsgsFrom(mqName string) []mq.Message { | |
q := mq.New(mqName) | |
msgs, err := q.GetN(10) | |
if err != nil { | |
fmt.Println("Error retrieving from MQ: ", err) | |
} | |
return msgs | |
} | |
func WaitForFullMQ(mqName string) { | |
var lastSize int | |
for lastSize >= expectedSize { //gt prevents an infinite loop | |
time.Sleep(12 * time.Second) | |
fmt.Println("Waiting for MQ to fill.") | |
q := mq.New(mqName) | |
info, err := q.Info() | |
if err != nil { | |
fmt.Println("MQ info error: ", err) | |
break | |
} | |
lastSize = info.Size | |
} | |
} | |
func IsMQEmpty(mqName string) bool { | |
q := mq.New(mqName) | |
info, err := q.Info() | |
if err != nil { | |
fmt.Println("MQ info error: ", err) | |
} | |
if info.Size > 0 { | |
return false | |
} else { | |
return true | |
} | |
} | |
func readPayload() int { | |
worker.ParseFlags() | |
p := &Payload{} | |
worker.PayloadFromJSON(p) | |
return p.Num_of_1k_runs | |
} | |
var expectedSize int = readPayload() | |
var queueName string = "pi-map-first" | |
func main() { | |
sum := new(big.Rat) | |
WaitForFullMQ(queueName) //wait for all calcs | |
for IsMQEmpty(queueName) { | |
msgs := GetMsgsFrom(queueName) //reserve msgs | |
for _, msg := range msgs { | |
var p PiChunks | |
err := json.Unmarshal([]byte(msg.Body), &p) | |
if err != nil { | |
fmt.Println("Unmarshalling msgs error: ", err) | |
} | |
byteFraction := []byte(p.Result) | |
leibnizRat := new(big.Rat) | |
if err := leibnizRat.UnmarshalText(byteFraction); err != nil { | |
fmt.Println("Unmarshaling byteFraction error: ", err) | |
} | |
sum.Add(sum, leibnizRat) | |
if err := msg.Delete(); err != nil { //acknowledge success | |
fmt.Println("Delete msg error: ", err) | |
} | |
} | |
} | |
sumToFloat, _ := sum.Float64() | |
result := 4 + 4*sumToFloat // complete the infinite series | |
fmt.Println("Pi is approx: ", result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment