numbers

package
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 1, 2024 License: BSD-3-Clause Imports: 11 Imported by: 6

Documentation

Overview

Package numbers provides a variety of functions related to statistics

Index

Constants

View Source
const Ln4 float64 = 1.38629436112
View Source
const MaxInt = 1<<(bits.UintSize-1) - 1
View Source
const MaxIterations int = 200
View Source
const MaxUint = 1<<bits.UintSize - 1
View Source
const MinInt = -MaxInt - 1
View Source
const RelError float64 = 1.0e-8
View Source
const Small float64 = 1.0e-30

Variables

This section is empty.

Functions

func AbsInt

func AbsInt(x int) int

AbsInt returns the absolute value of an input of type int.

func AdaptiveSimpsons

func AdaptiveSimpsons(f func(float64) float64, a float64, b float64, errorThreshold float64, maxDepth int) float64

AdaptiveSimpsons returns the integral from a to b of function f The error in the calculation should be less than or equal to errorThreshold. If this can not be achieved within maxDepth number recursions, then the function aborts.

func AdaptiveSimpsonsLog

func AdaptiveSimpsonsLog(f func(float64) float64, a float64, b float64, errorThreshold float64, maxDepth int) float64

AdaptiveSimpsons returns the log of the integral from a to b of g(x), where f(x) = log(g(x)) The error in the calculation should be less than or equal to errorThreshold. If this can not be achieved within maxDepth number recursions, then the function aborts.

func AddBinomMapEntry

func AddBinomMapEntry(n int) []float64

AddBinomMapEntry adds an entry to a binomMap containing a slice of binomial coefficients in logSpace for a particular n value.

func ApproxEqual added in v1.0.1

func ApproxEqual(a, b, epsilon float64) bool

ApproxEqual determines if two floating-point numbers are equal within a specified tolerance level.

func AverageFloat64

func AverageFloat64(f []float64) float64

AverageFloat64 returns the mean value of type float64 from a slice of type float64.

func BetaClosure

func BetaClosure(alpha float64, beta float64) func(float64) float64

BetaClosure returns an instantiation of a Beta Distribution with fixed alpha and beta parameters.

func BetaDist

func BetaDist(x float64, alpha float64, beta float64) float64

BetaDist returns the probability density of a beta distribution with parameters alpha and beta at position x.

func BetaFunc

func BetaFunc(x float64, y float64) float64

BetaFunc returns B(x, y), where B is the Beta Function, also known as the Euler integral of the first kind.

func BetaIntegral

func BetaIntegral(left float64, right float64, alpha float64, beta float64) float64

BetaIntegral calculates the integral under a beta distribution with parameters alpha and beta between a specified left and right bound.

func BetaLeftIntegral

func BetaLeftIntegral(x float64, alpha float64, beta float64) float64

BetaLeftIntegral returns the integral to the left of an input point x from a beta distribution with parameters alpha and beta.

func BetaRightIntegral

func BetaRightIntegral(x float64, alpha float64, beta float64) float64

BetaRightIntegral returns the integral to the right of an input point x from a beta distribution with parameters alpha and beta.

func BetaSampler

func BetaSampler(a float64, b float64) func() (float64, float64)

BetaSampler returns an instantiation of RandBeta for a specified a and b parameter.

func BinomCoefficient

func BinomCoefficient(n int, k int) int

BinomCoefficient calculates the Binomial Coefficient, which is also called the "Choose" Function. The answer returned is "n choose k" or n!/(n-k)!k!

func BinomCoefficientLog

func BinomCoefficientLog(n int, k int) float64

BinomCoefficientLog returns log(n choose k), where log is the natural logarithm. Ideal for large numbers as this raises the overflow ceiling considerably.

func BinomialDist

func BinomialDist(n int, k int, p float64, logOutput bool) (float64, bool)

BinomialDist returns the probability mass from a binomial distribution with k successes out of n observations with success probability p. The second return is false if no overflow/underflow was detected. If underflow was detected, the program returns 0 and true. If logOutput is true, answer will be returned as log(answer).

func BinomialDistLog

func BinomialDistLog(n int, k int, p float64) float64

BinomialDistLog returns log(BinomialDist), where log is the natural logarithm. This is ideal for very small probabilities to avoid underflow.

func BinomialDistLogSlice

func BinomialDistLogSlice(n int, k int, p float64, binomCache [][]float64) float64

BinomialDistLogSlice returns log(BinomialDist), where log is the natural logarithm. This function is similar to BinomialDistLog but passes in a map[int][]float64, where the int key refers to n and the []float64 map values are the corresponding binomial coefficients for index k. Useful to not recalculate the binomial coefficient each time when binomial densities must be constantly evaluated in logSpace, like in MCMC.

func BinomialExpressionLog

func BinomialExpressionLog(n int, k int, p float64) float64

BinomialExpressionLog returns p^n * (1 - p)^n-k, which is also referred to as the binomial expression. The answer is provided in logSpace (.

func BinomialLeftSummation

func BinomialLeftSummation(n int, k int, p float64, logOutput bool) float64

BinomialLeftSummation calculates the sum of binomial probabilities to the left of k successes for a binomial distribution with n experiments and a success probability of p, inclusive.

func BinomialRightSummation

func BinomialRightSummation(n int, k int, p float64, logOutput bool) float64

BinomialRightSummation calculates the sum of binomial probabilities to the right of k successes for a binomial distribution with n experiments and a success probability of p, inclusive.

func BinomialSum

func BinomialSum(left int, right int, n int, p float64, logOutput bool) float64

BinomialSum calculates the sum of probabilities in a binomial distribution with n experiments and success probability p between two input k values. Inclusive on both ends.

func BoundedRejectionSample

func BoundedRejectionSample(boundingSampler func() (float64, float64), f func(float64) float64, xLeft float64, xRight float64, maxIteration int) (float64, float64)

BoundedRejectionSample returns a rejection sample of a function f using a bounding function boundingSampler between a specified left and right bound.

func DefiniteIntegral

func DefiniteIntegral(f func(float64) float64, start float64, end float64) float64

DefiniteIntegral computes the definite integral of f(x) dx from start to end.

func DefiniteSmallIntegral

func DefiniteSmallIntegral(f func(float64) float64, start float64, end float64) float64

DefiniteSmallIntegral is like DefiniteIntegral with absolute error set to zero, so only relative error defines convergence conditions. slower than DefiniteIntegral, but more accurate for small values.

func DigitsBaseTen

func DigitsBaseTen(x int) int

DigitsBaseTen returns the.

func DiscardBurnIn

func DiscardBurnIn(t McmcTrace, burnIn int)

DiscardBurnIn will remove the the first i values in an McmcTrace, where i is equal to the input value burnIn.

func ExpDist

func ExpDist(x float64) float64

ExpDist returns the density of the standard exponential distribution y=e^-x.

func Factorial

func Factorial(n int) int

Factorial returns n! in normal space.

func FastRejectionSampler

func FastRejectionSampler(xLeft float64, xRight float64, f func(float64) float64, bins int, maxSampleDepth int, samples int) []float64

FastRejectionSampler returns simulated values from an a func(float64) float64 between a left and right value using an optimized rejection sampler that divides the function support into discrete bins with optimized sampling heights. maxSampleDepth triggers the log.Fatalf in the RejectionSample func, and samples is the number of values to be returned.

func FisherExact

func FisherExact(a, b, c, d int, aSmall bool) float64

FisherExact computes a one-sided Fisher's Exact test on the 2x2 table provided The test is for the matrix: [a b] [c d] aSmall being true tests for the ratio of a to b being small, given the ratio of c to d aSmall being false tests for the ratio of a to b being large, given the ratio of c to d.

func GammaClosure

func GammaClosure(alpha float64, beta float64) func(float64) float64

GamaClosure returns an instantiation of a Gamma Distribution with fixed alpha and beta parameters.

func GammaDist

func GammaDist(x float64, alpha float64, beta float64) float64

GammaDist returns the probability density of a gamma distribution with parameters alpha and beta at position x. alpha is the shape parameter and beta is the rate parameter.

func GammaIntegral

func GammaIntegral(left float64, right float64, alpha float64, beta float64) float64

GammaIntegral calculates the integral between an input left and right bound of a gamma distribution with parameters alpha and beta.

func GammaLeftIntegral

func GammaLeftIntegral(x float64, alpha float64, beta float64) float64

GammaLeftIntegral calculates the integral to the left of an input position on a gamma distribution with parameters alpha and beta.

func GammaRightIntegral

func GammaRightIntegral(x float64, alpha float64, beta float64) float64

GammaRightIntegral calculates the integral to the right of an input position on a gamma distribution with parameters alpha and beta.

func GammaSampler

func GammaSampler(a float64, b float64) func() (float64, float64)

GammaSampler returns an instantiation of RandGamma for specified a and b parameters.

func GeometricDist

func GeometricDist(k int, p float64) float64

GeometricDist returns the density of the geometric for k failures with success probability p. Note that this is the version of the geometric distribution with support from 0 to +INF.

func GoldenSectionMaxSearch

func GoldenSectionMaxSearch(f func(float64) float64, a float64, b float64, epsilon float64) float64

GoldenSectionMaxSearch returns returns a local maximum for the input range a to b from an input function f with a user specified error epsilon. For unimodal functions, we are guaranteed to find the maximum if it is contained within the interval a to b. For polymodal functions, this function will converge on one of its modes contained in the interval a to b.

func GoldenSectionMinSearch

func GoldenSectionMinSearch(f func(float64) float64, a float64, b float64, epsilon float64) float64

GoldenSectionMinSearch returns a local minimum for the input range a to b from an input function f with a user specified error epsilon. For a unimodal function, we are guaranteed to find the minimum if it is contained within the interval a to b. For polymodal functions, this function will converge on one of its modes contained in the interval a to b.

func HighestDensityInterval

func HighestDensityInterval(t McmcTrace, proportion float64) (float64, float64)

HighestDensityInterval returns the HDI credible interval for an input McmcTrace struct. Proportion is the proportion of iterations in the credible interval (ex. 0.95 for a 95% credible interval).

func InitializeFastRejectionSampler

func InitializeFastRejectionSampler(xLeft float64, xRight float64, f func(float64) float64, bins int) ([]float64, float64)

InitializeFastRejectionSampler takes in the parameters of a rejection sampler and returns the binHeights and sumHeights variables.

func LogIntegrate

func LogIntegrate(f func(float64) float64, a float64, b float64, n int) float64

LogIntegrate evaluates log(int_a^b f(x)dx) in cases where f returns log(f(x)). Uses the rectangle rule.

func LogIntegrateIterative

func LogIntegrateIterative(f func(float64) float64, a float64, b float64, maxIter int, relativeError float64) float64

LogIntegrateIterative repeatedly calls LogIntegrate with progressively more bins until the relative error between iterations is less than the relativeError inut variable. Each interation uses 10x more bins.

func Max

func Max[E constraints.Ordered](a, b E) E

Max returns the maximum of two input values of an ordered type.

func MaxMany

func MaxMany[E constraints.Ordered](s ...E) E

MaxMany returns the maximum of any number of input values of an ordered type.

func MeanMcmcTrace

func MeanMcmcTrace(t McmcTrace) float64

MeanMcmcTrace returns the mean value of the posterior distribution estimated by an McmcTrace.

func Min

func Min[E constraints.Ordered](a, b E) E

Min returns the minimum of two input values of an ordered type.

func MinMany

func MinMany[E constraints.Ordered](s ...E) E

MinMany returns the minimum of any number of input values of an ordered type.

func NegativeBinomialCdf added in v1.0.1

func NegativeBinomialCdf(x float64, R float64, P float64) float64

NegativeBinomialCdf returns the CDF of the negative binomial distribution for an input score x for a distribution defined by parameters R and P.

func NegativeBinomialDist added in v1.0.1

func NegativeBinomialDist(k int, r float64, p float64, logOutput bool) (float64, bool)

NegativeBinomialDist returns the probability mass of a negative binomial distribution with shape parameter r and success probability p at k. Pr(X = k) the second return is true if overflow/underflow was detected.

func NormalAdaptiveIntegral

func NormalAdaptiveIntegral(left string, right string, mu float64, sigma float64) float64

NormalAdaptiveIntegral returns the integral under a normal probability distribution with mean mu and standard deviation sigma from a specified left and right bound.

func NormalClosure

func NormalClosure(mu float64, sigma float64) func(float64) float64

NormalClosure returns an instantiation of a normal distribution for a particular mean mu and standard deviation sigma.

func NormalDist

func NormalDist(x float64, mu float64, sigma float64) float64

NormalDist returns the normal distribution value x for a distribution with mean mu and standard deviation sigma.

func NormalLeftIntegral

func NormalLeftIntegral(x float64, mu float64, sigma float64) float64

NormalLeftIntegral returns the area under the curve of an input normal probability distribution defined by mean (mu) and standard deviation (sigma) to the left of an input point x.

func NormalRightIntegral

func NormalRightIntegral(x float64, mu float64, sigma float64) float64

NormalLeftIntegral returns the area under the curve of an input normal probability distribution defined by mean (mu) and standard deviation (sigma) to the right of an input point x.

func Pearson

func Pearson(a []float64, b []float64) float64

Pearson calculates the Pearson Correlation Coefficient between two slices of float64.

func Plot

func Plot(f func(float64) float64, left float64, right float64, bins int, outFile string)

Plot returns the values of a function(float64) float64 between a left and right bound for a specified number of bins. the answer is written to a file as a CSV for subsequent visualization. Half-closed interval [left, right).

func PlotBinomCoefficient

func PlotBinomCoefficient(n int, outFile string)

PlotBinomCoefficient writes binomial coefficients (n choose k) from k=1 to k=n-1 to an output file for downstream visualization.

func PoissonDist

func PoissonDist(k int, lambda float64) float64

PoissonDist returns the probability density of a poisson distribution with parameter lambda at the integer value k.

func PoissonLeftSummation

func PoissonLeftSummation(k int, lambda float64) float64

PoissonLeftSummation calculates the sum of probabilities to the left of an integer k, inclusive.

func PoissonRightSummation

func PoissonRightSummation(k int, lambda float64) float64

PoissonRightSummation calculates the sum of probabilities to the right of an integer k, inclusive.

func PoissonSum

func PoissonSum(left int, right int, lambda float64) float64

PoissonSum calculates the sum of probabilities between an input left and right bound, inclusive on both ends.

func RandBeta

func RandBeta(a float64, b float64) float64

RandBeta is the basic beta variate generator from Cheng 1978. Uses the BA algorithm, which is less optimized, but still runs effectively for my use case. More optimized algorithms (with greater programming complexity) are described in the Cheng paper, and should be implemented (TODO) if required.

func RandBinomial

func RandBinomial(alias BinomialAlias) int

RandBinomial generates binomial distributed variates from a pre-generated BinomialAlias struct, which can be made for a specified binomial distribution with 'MakeBinomialAlias'.

func RandExp

func RandExp() (float64, float64)

RandExp Returns a random variable as a float64 from a standard exponential distribution. f(x)=e**-x. Algorithm from Ahrens, J.H. and Dieter, U. (1972). Computer methods for sampling from the exponential and normal distributions. Comm. ACM, 15, 873-882.

func RandFloat64InRange

func RandFloat64InRange(x float64, y float64) float64

RandFloat64InRange returns a pseudorandom value of type int between x and y.

func RandGamma

func RandGamma(a float64, b float64) (float64, float64)

RandGamma returns a random x,y point drawn from a gamma distribution with parameters alpha and beta. y corresponds to the function density at that x value. a > 1 uses the method from Marsaglia and Tsang 2000. Written for k, theta parameters, so the first step converts b to 1 / b to evaluate gamma in terms of alpha and beta parameters. a < 1 uses the method from Ahrens, J.H. and Dieter, U. (1974). Computer methods for sampling from gamma, beta, poisson and binomial distributions. Computing, 12, 223-246.

func RandGeometric

func RandGeometric(p float64) int

RandGeometric returns a geometrically-distributed random variate using the inverse transform. Note the geometric distribution has CDF: F(x) = 1 - (1-p)^x. The inverse transform is derived as (1-p)^x = 1 - F(x) -> x*log(1-p) = log(1 - F(x)) -> x = log(1 - F(x)) / log(1-p). Note that this is the version of the geometric distribution with support from 0 to +INF.

func RandInt64InRange

func RandInt64InRange(x int64, y int64) int64

RandInt64InRange returns a pseudorandom value of type int64 between x and y. Output includes x, but not y.

func RandIntInRange

func RandIntInRange(x int, y int) int

RandIntInRange returns a pseudorandom value of type int between x and y. Output includes x, but not y.

func RegularizedIncompleteBeta added in v1.0.1

func RegularizedIncompleteBeta(a float64, b float64, x float64) float64

RegularizedIncompleteBeta computes the Regularized Incomplete Beta Function for parameters A and B at query point X. Translation of an implementation at Copyright (c) 2016, 2017 Lewis Van Winkle, zlib license. https://codeplea.com/incomplete-beta-function-c

func RejectionSample

func RejectionSample(xLeft float64, xRight float64, yMax float64, f func(float64) float64, maxIteration int) float64

RejectionSample returns simulated values from an arbitrary function between a specified left and right bound using a simple rejection sampling method.

func RejectionSampleChooseBin

func RejectionSampleChooseBin(xLeft float64, xRight float64, stepSize float64, f func(float64) float64, maxIteration int, sumHeights float64, binHeights []float64) float64

RejectionSampleChooseBin is a helper function of FAstRejectionSampler.

func SampleInverseNormal

func SampleInverseNormal(mu float64, sigma float64) float64

SampleInverseNormal returns a simulated value from a normal distribution.

func ScaledBetaSampler

func ScaledBetaSampler(a float64, b float64, multiplier float64) func() (float64, float64)

ScaledBetaSampler returns an instatiation of RandBeta where the returned density has been scaled by the input variable 'multiplier'.

func StandardDeviationFloat64

func StandardDeviationFloat64(f []float64) float64

StandardDeviationFloat64 returns the standard deviation (type float64) from a slice of type float64.

func StandardNormalDist

func StandardNormalDist(x float64) float64

StandardNormalDist returns the probability density for an input x value on a standard normal distribution (mu=0, sigma=1).

func VarianceFloat64

func VarianceFloat64(f []float64) float64

VarianceFloat64 returns the variance (type float64) from a slice of type float64.

Types

type BinomialAlias

type BinomialAlias struct {
	Probability []float64
	Alias       []int
}

BinomialAlias contains alias table information used to generate binomial distributed random variates for pre-specified parameters. Setting up the BinomialAlias struct runs in O(n) time. However, once the alias is set up for a fixed cost, random variates can be generated from the distribution in O(1) time. More information on the alias method can be found here: https://en.wikipedia.org/wiki/Alias_method

func MakeBinomialAlias

func MakeBinomialAlias(n int, p float64) BinomialAlias

MakeBinomialAlias generates a BinomialAlias struct for a specified binomial distribution of n trials with success probability p. Note if the probability of a binomial outcome is less than math.MinFloat64, it will never be generated. This implementation therefore draws variates from an approximation of the binomial distribution that is truncated to zero when its tail crosses below the float underflow threshold.

type McmcTrace

type McmcTrace struct {
	Parameter []float64 //Parameter state, where Parameter[i] is the value of Parameter in the ith iteration.
}

McmcTrace is a general struct for Mcmc trace output. Used for discarding burn-in and calculating the mean and credible interval.

func ReadMcmcTrace

func ReadMcmcTrace(inFile string, parameterName string) McmcTrace

ReadMcmcTrace takes a filename of the trace output file and a parameter name of interest. The function returns the values of that parameter across the Mcmc run.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL