Guest User

Untitled

a guest
Jan 22nd, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. % cat main.go
  2. package main
  3.  
  4. import "flag"
  5. import "fmt"
  6. import "math"
  7. import "rand"
  8. import "time"
  9.  
  10. var numprocs *int = flag.Int("procs", 4, "number of processors")
  11. var iterations *int = flag.Int("iter", int(1e6), "number of iterations per proc")
  12.  
  13. func pi(max_iterations int, r chan float64) {
  14. successes := 0
  15.  
  16. var x float64
  17. var y float64
  18.  
  19. for i := 0; i <= max_iterations; i++ {
  20. x = rand.Float64()
  21. y = rand.Float64()
  22.  
  23. if math.Sqrt(x*x + y*y) <= 1.0 {
  24. successes++
  25. }
  26. }
  27.  
  28. fmt.Println(successes, max_iterations)
  29.  
  30. fraction := float64(successes) / float64(max_iterations)
  31. r <- fraction * 4
  32. }
  33.  
  34. func main() {
  35. flag.Parse()
  36. rand.Seed(time.Nanoseconds())
  37. fmt.Println(*numprocs)
  38.  
  39. pcount := *numprocs
  40. iteration_count := *iterations
  41.  
  42. r := make(chan float64, pcount)
  43.  
  44. for i := 0; i < pcount; i++ {
  45. go pi(iteration_count, r)
  46. }
  47.  
  48. var total float64 = 0.0
  49. for i := 0; i < pcount; i++ {
  50. result := <-r
  51. total += result
  52. }
  53.  
  54. fmt.Println(total / float64(pcount))
  55. }
Add Comment
Please, Sign In to add comment