File: geometric_distribution.go

package info (click to toggle)
golang-github-montanaflynn-stats 0.7.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 460 kB
  • sloc: makefile: 27
file content (42 lines) | stat: -rw-r--r-- 1,037 bytes parent folder | download
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
package stats

import (
	"math"
)

// ProbGeom generates the probability for a geometric random variable
// with parameter p to achieve success in the interval of [a, b] trials
// See https://en.wikipedia.org/wiki/Geometric_distribution for more information
func ProbGeom(a int, b int, p float64) (prob float64, err error) {
	if (a > b) || (a < 1) {
		return math.NaN(), ErrBounds
	}

	prob = 0
	q := 1 - p // probability of failure

	for k := a + 1; k <= b; k++ {
		prob = prob + p*math.Pow(q, float64(k-1))
	}

	return prob, nil
}

// ProbGeom generates the expectation or average number of trials
// for a geometric random variable with parameter p
func ExpGeom(p float64) (exp float64, err error) {
	if (p > 1) || (p < 0) {
		return math.NaN(), ErrNegative
	}

	return 1 / p, nil
}

// ProbGeom generates the variance for number for a
// geometric random variable with parameter p
func VarGeom(p float64) (exp float64, err error) {
	if (p > 1) || (p < 0) {
		return math.NaN(), ErrNegative
	}
	return (1 - p) / math.Pow(p, 2), nil
}