Repository navigation
Expand file tree
/
Copy pathprobability.go
More file actions
83 lines (74 loc) · 1.48 KB
/
Copy pathprobability.go
File metadata and controls
83 lines (74 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package probability
import (
"errors"
"fmt"
"math"
"math/rand"
)
const Σ = 1.0
const MU = 0.0
const TOLERANCE = 0.00001
func UniformPdf(x float64) (result int) {
result = 0
if x >= 0 && x < 1 {
result = 1
}
return
}
func UniformCdf(x float64) (result float64) {
result = 1
if x < 0 {
result = 0
} else if x < 1 {
result = x
}
return
}
func NormalPdf(x, mu, σ float64) float64 {
sqrtTwoPi := math.Sqrt(2 * math.Pi)
powXmu := math.Pow((x - mu), 2)
exp := math.Exp(-(powXmu / (2 * math.Pow(σ, 2))))
return exp / (sqrtTwoPi * σ)
}
func NormalCdf(x, μ, σ float64) float64 {
erf := math.Erf((x - μ) / math.Sqrt2 / σ)
return (1 + erf) / float64(2)
}
func InverseNormalCdf(p, μ, σ, tolerance float64) float64 {
if μ != MU || σ != Σ {
return μ + σ*InverseNormalCdf(p, MU, Σ, tolerance)
}
lowZ := -10.0
hiZ := 10.0
var midZ, midP float64
for hiZ-lowZ > tolerance {
midZ = (lowZ + hiZ) / float64(2)
midP = NormalCdf(midZ, MU, Σ)
if midP < p {
lowZ = midZ
} else if midP > p {
hiZ = midZ
} else {
break
}
}
return midZ
}
func BernoulliTrial(p float64) (result int64) {
if rand.Float64() < p {
result = 1
}
return
}
func Binomial(p float64, n int) (result int64, err error) {
if !(0.0 <= p && p <= 1.0) {
return -1, errors.New(fmt.Sprintf("Invalid probability p: %f", p))
}
if n <= 0 {
return -1, errors.New(fmt.Sprintf("Invalid parameter n: %d", n))
}
for i := 1; i <= n; i++ {
result += BernoulliTrial(p)
}
return result, nil
}