Generating numbers from normal distribution in Python
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Track title: CC G Dvoks String Quartet No 12 Ame 2
--
Chapters
00:00 Generating Numbers From Normal Distribution In Python
00:30 Accepted Answer Score 3
01:16 Thank you
--
Full question
https://stackoverflow.com/questions/3327...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #normaldistribution
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Track title: CC G Dvoks String Quartet No 12 Ame 2
--
Chapters
00:00 Generating Numbers From Normal Distribution In Python
00:30 Accepted Answer Score 3
01:16 Thank you
--
Full question
https://stackoverflow.com/questions/3327...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #normaldistribution
#avk47
ACCEPTED ANSWER
Score 3
For "fun", I wrote it up in go. The box_muller function is faster there as well. Also, it's about 10 times faster than the python version.
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
now := time.Now()
for i := 0; i < 1000000; i++ {
marsaglia_polar()
}
fmt.Println("marsaglia_polar duration = ", time.Since(now))
now = time.Now()
for i := 0; i < 1000000; i++ {
box_muller()
}
fmt.Println("box_muller duration = ", time.Since(now))
}
func marsaglia_polar() (float64, float64) {
for {
x := random() * 2 - 1;
y := random() * 2 - 1;
s := x * x + y * y;
if s < 1 {
t := math.Sqrt((-2) * math.Log(s)/s);
return x * t, y * t
}
}
}
func box_muller() (float64, float64) {
u1 := random()
u2 := random()
t := math.Sqrt((-2) * math.Log(u1))
v := 2 * math.Pi * u2
return t * math.Cos(v), t * math.Sin(v)
}
func random() float64 {
return rand.Float64()
}
Output:
marsaglia_polar duration = 104.308126ms
box_muller duration = 88.365933ms