Class Maths
-
- All Implemented Interfaces:
public class MathsMathematical functions and utilities.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description public classMaths.laplaceApproxComplexReturnpublic classMaths.laplaceApproxReturnpublic classMaths.simplexQuadResult
-
Constructor Summary
Constructors Constructor Description Maths()
-
Method Summary
Modifier and Type Method Description static doublebinomialCoeff(int n, int k)Computes the binomial coefficient "n choose k" by doing the work in log-space then exponentiating with FastMath.exp(). static Matrixcircul(int c)Returns a circulant matrix of order c. static Matrixcircul(Matrix c)Returns a circulant matrix from the given first column. static Array<int>cumSum(Array<int> ar)Cumulative sum of an array, where the value at each index of the result is the sum of all the previous values of the input. static Array<double>cumSum(Array<double> ar)Cumulative sum of an array, where the value at each index of the result is the sum of all the previous values of the input. static voidelementAdd(Array<int> ar, int i)Helper method that adds an integer to every element of an integer array. static doublenormalErf(double x)Computes the error function (erf) of a value. static MatrixmatrixExp(Matrix matrix)Adapted from jblas and IHMC Original documentation: Calculate matrix exponential of a square matrix. static intfact(int n)Computes the factorial of an integer. static doublefact(double n)Computes the factorial of a double value using the gamma function. static doublefactln(int n)Computes the natural logarithm of the factorial. static doublefactln(double n)Computes the natural logarithm of the factorial for a double value. static doublegammaFunction(double x)Computes the gamma function via Lanczos approximation formula. static Maths.simplexQuadResultgrnmol(Function<Array<double>, Double> f, Array<Array<double>> V, int s, double tol)Grundmann-Moeller simplex integration static MatrixbinHist(Matrix v, int minVal, int maxVal)Implementation of MATLAB "hist": puts elements of v into k bins static Maths.laplaceApproxReturnlaplaceapprox_h(Matrix x0, SerializableFunction<Matrix, Matrix> h)static Maths.laplaceApproxComplexReturnlaplaceapprox_h_complex(Matrix x0, SerializableFunction<Matrix, ComplexMatrix> h)static Array<double>linSpace(double start, double end, int num)static doublelogBinomial(int n, int k)Computes log(n choose k) = log Γ(n+1) − log Γ(k+1) − log Γ(n−k+1). static doublelogmeanexp(Matrix x)static Array<double>logSpace(double min, double max, int n)static Array<int>logSpacei(int start, int stop, int n)Generates an integer list of n logarithmically spaced values. static doublemax(double x, double y)Returns the max of two numbers. static doublemin(double x, double y)Returns the min of two numbers. static List<Matrix>multiChooseCombinations(int k, int n)Generate all combinations of distributing n items into k bins static MatrixmultiChooseCon(Matrix n, double S)static Matrixmultichoose(double n, double k)static doublemultinomialln(Matrix n)static doublenCk(double n, double k)static MatrixnCk(Matrix v, int k)Computes the combinations of the elements in v taken k at a time static intnextPowerOfTwo(int x)Given an integer x input, find the next integer y greater than x such that y is a power of 2. static Matrixnum_grad_h(Matrix x0, double h, SerializableFunction<Matrix, Matrix> hfun)static ComplexMatrixnum_grad_h_complex(Matrix x0, double h, SerializableFunction<Matrix, ComplexMatrix> hfun)static Matrixnum_hess_h(Matrix x0, double h, SerializableFunction<Matrix, Matrix> hfun)static ComplexMatrixnum_hess_h_complex(Matrix x0, double h, SerializableFunction<Matrix, ComplexMatrix> hfun)static Matrixpermutations(Matrix vec)static doublerand()static doublerandn()static intprobchoose(List<Double> p)Choose an element index according to probability vector. static intprobchoose(Matrix p)Choose an element index according to probability vector. static List<Integer>primes(int N)static intmaxpos(Matrix v)Returns the position of the maximum value in a vector. static Array<int>maxpos(Matrix v, int n)Returns the positions of the n largest values in a vector. static intminpos(Matrix v)Returns the position of the minimum value in a vector. static Array<int>minpos(Matrix v, int n)Returns the positions of the n smallest values in a vector. static booleanrandomMatlabStyle()static Array<Complex>roots(Matrix coefficients)static Array<Complex>roots(Array<double> coefficients)static voidsetMatlabRandomSeed(long seed)static voidsetRandomNumbersMatlab(boolean matlab_style)static doublesimplex_fun(Array<double> x, Matrix L, Matrix N)Computes a specialized function used in simplex-based optimization algorithms. static Maths.simplexQuadResultsimplexquad(Function<Array<double>, Double> f, int n, int order, double tol)static doublesoftmin(double x, double y, double alpha)Softmin function. static List<Integer>sub2ind(Matrix dims, Matrix row, Matrix col)static Array<Array<double>>transpose(Array<Array<double>> data)Transposes a 2D array of values. static MatrixuniqueAndSort(Matrix space)static MatrixuniquePerms(Matrix vec)static Matrixsetdiff(Matrix A, Matrix B)Set difference operation for Matrix objects that are vectors. static Matrixmultichoose(int n, int k)Generates all combinations of n objects taken k at a time with repetition (multichoose). static List<Array<int>>multichooseList(int n, int k)Generates all combinations of n objects taken k at a time with repetition (multichoose). static List<Array<int>>sortByNnzPos(List<Array<int>> combinations)Sorts combinations by number of non-zeros and their positions. static intnnzcmp(Array<int> i1, Array<int> i2)Compares two arrays by number of zeros and their positions. static intmatchRow(List<Array<int>> rows, Array<int> target)Finds the index of a matching row in a list. static intnchoosek(int n, int k)Computes binomial coefficient "n choose k". static Array<double>goldenSectionSearch(Function<Double, Double> function, double a, double b, double tol)Golden section search for finding the minimum of a unimodal function. static Array<double>goldenSectionSearch(Function<Double, Double> function, double a, double b)Golden section search with default tolerance. -
-
Method Detail
-
binomialCoeff
static double binomialCoeff(int n, int k)
Computes the binomial coefficient "n choose k" by doing the work in log-space then exponentiating with FastMath.exp().
- Parameters:
n- total itemsk- items chosen- Returns:
the binomial coefficient, or 0.0 if k<0 or k>n
-
circul
static Matrix circul(int c)
Returns a circulant matrix of order c. Creates a circulant matrix where each row is a cyclic shift of the previous row.
- Parameters:
c- the order of the circulant matrix- Returns:
a c×c circulant matrix
-
circul
static Matrix circul(Matrix c)
Returns a circulant matrix from the given first column. Creates a circulant matrix where the first column is given by the input matrix, and each subsequent column is a cyclic shift of the previous one.
- Parameters:
c- the first column of the circulant matrix- Returns:
a square circulant matrix
-
cumSum
static Array<int> cumSum(Array<int> ar)
Cumulative sum of an array, where the value at each index of the result is the sum of all the previous values of the input.
- Parameters:
ar- Array we want the cumulative sum of.- Returns:
New array that is the cumulative sum of the input.
-
cumSum
static Array<double> cumSum(Array<double> ar)
Cumulative sum of an array, where the value at each index of the result is the sum of all the previous values of the input.
- Parameters:
ar- Array we want the cumulative sum of.- Returns:
New array that is the cumulative sum of the input.
-
elementAdd
static void elementAdd(Array<int> ar, int i)
Helper method that adds an integer to every element of an integer array.
- Parameters:
ar- Array to be added to.i- Integer to add.
-
normalErf
static double normalErf(double x)
Computes the error function (erf) of a value. The error function is the integral of the Gaussian distribution.
- Parameters:
x- the input value- Returns:
the error function value erf(x)
-
matrixExp
static Matrix matrixExp(Matrix matrix)
Adapted from jblas and IHMC Original documentation:
Calculate matrix exponential of a square matrix.
A scaled Pade approximation algorithm from Golub and Van Loan "Matrix Computations", algorithm 11.3.1 and 11.2.
- Returns:
matrix exponential of the matrix
-
fact
static int fact(int n)
Computes the factorial of an integer.
- Parameters:
n- the input value- Returns:
n! (n factorial)
-
fact
static double fact(double n)
Computes the factorial of a double value using the gamma function.
- Parameters:
n- the input value- Returns:
n! = Γ(n+1)
-
factln
static double factln(int n)
Computes the natural logarithm of the factorial.
- Parameters:
n- the input value- Returns:
ln(n!)
-
factln
static double factln(double n)
Computes the natural logarithm of the factorial for a double value.
- Parameters:
n- the input value- Returns:
ln(n!) = ln(Γ(n+1))
-
gammaFunction
static double gammaFunction(double x)
Computes the gamma function via Lanczos approximation formula. The gamma function is an extension of the factorial function to real and complex numbers.
- Parameters:
x- the input value- Returns:
Γ(x)
-
grnmol
static Maths.simplexQuadResult grnmol(Function<Array<double>, Double> f, Array<Array<double>> V, int s, double tol)
Grundmann-Moeller simplex integration
-
binHist
static Matrix binHist(Matrix v, int minVal, int maxVal)
Implementation of MATLAB "hist": puts elements of v into k bins
- Parameters:
v- - vector of elementsminVal- - lowest number in vmaxVal- - highest number in v- Returns:
- vector containing number of elements in each bin
-
laplaceapprox_h
static Maths.laplaceApproxReturn laplaceapprox_h(Matrix x0, SerializableFunction<Matrix, Matrix> h)
-
laplaceapprox_h_complex
static Maths.laplaceApproxComplexReturn laplaceapprox_h_complex(Matrix x0, SerializableFunction<Matrix, ComplexMatrix> h)
-
logBinomial
static double logBinomial(int n, int k)
Computes log(n choose k) = log Γ(n+1) − log Γ(k+1) − log Γ(n−k+1). Uses Commons-Math Gamma but FastMath for everything else.
- Parameters:
n- total itemsk- items chosen- Returns:
log of the binomial coefficient, or NegInf if k<0 or k>n
-
logmeanexp
static double logmeanexp(Matrix x)
-
logSpacei
static Array<int> logSpacei(int start, int stop, int n)
Generates an integer list of n logarithmically spaced values.
- Parameters:
start- First element of array.stop- Last element of array.n- Number of values.- Returns:
Array of logarithmically spaced values.
-
max
static double max(double x, double y)
Returns the max of two numbers. If one of the two is NaN, it returns the other.
- Parameters:
x- - the first number to be comparedy- - the second number to be compared- Returns:
- the max between the two
-
min
static double min(double x, double y)
Returns the min of two numbers. If one of the two is NaN, it returns the other.
- Parameters:
x- - the first number to be comparedy- - the second number to be compared- Returns:
- the min between the two
-
multiChooseCombinations
static List<Matrix> multiChooseCombinations(int k, int n)
Generate all combinations of distributing n items into k bins
-
multiChooseCon
static Matrix multiChooseCon(Matrix n, double S)
-
multichoose
static Matrix multichoose(double n, double k)
-
multinomialln
static double multinomialln(Matrix n)
-
nCk
static double nCk(double n, double k)
-
nCk
static Matrix nCk(Matrix v, int k)
Computes the combinations of the elements in v taken k at a time
- Parameters:
v- - vector of elementsk- - how many elements to pick at a time- Returns:
- the combinations of the elements in v taken k at a time
-
nextPowerOfTwo
static int nextPowerOfTwo(int x)
Given an integer x input, find the next integer y greater than x such that y is a power of 2.
- Parameters:
x- Input to find next power- Returns:
Closest integer greater than input that is a power of two.
-
num_grad_h
static Matrix num_grad_h(Matrix x0, double h, SerializableFunction<Matrix, Matrix> hfun)
-
num_grad_h_complex
static ComplexMatrix num_grad_h_complex(Matrix x0, double h, SerializableFunction<Matrix, ComplexMatrix> hfun)
-
num_hess_h
static Matrix num_hess_h(Matrix x0, double h, SerializableFunction<Matrix, Matrix> hfun)
-
num_hess_h_complex
static ComplexMatrix num_hess_h_complex(Matrix x0, double h, SerializableFunction<Matrix, ComplexMatrix> hfun)
-
permutations
static Matrix permutations(Matrix vec)
-
rand
static double rand()
-
randn
static double randn()
-
probchoose
static int probchoose(List<Double> p)
Choose an element index according to probability vector. Equivalent to MATLAB's probchoose function.
- Parameters:
p- Probability vector (must sum to 1.- Returns:
Index of chosen element (0-based)
-
probchoose
static int probchoose(Matrix p)
Choose an element index according to probability vector. Overloaded version for Matrix input.
- Parameters:
p- Probability matrix (single row or column)- Returns:
Index of chosen element (0-based)
-
maxpos
static int maxpos(Matrix v)
Returns the position of the maximum value in a vector. Equivalent to MATLAB's maxpos function.
- Parameters:
v- Input vector- Returns:
Index of maximum value (0-based)
-
maxpos
static Array<int> maxpos(Matrix v, int n)
Returns the positions of the n largest values in a vector. Equivalent to MATLAB's maxpos(v, n) function.
- Parameters:
v- Input vectorn- Number of positions to return- Returns:
Array of indices of n largest values (0-based), sorted by value (descending)
-
minpos
static int minpos(Matrix v)
Returns the position of the minimum value in a vector. Equivalent to MATLAB's minpos function.
- Parameters:
v- Input vector- Returns:
Index of minimum value (0-based)
-
minpos
static Array<int> minpos(Matrix v, int n)
Returns the positions of the n smallest values in a vector. Equivalent to MATLAB's minpos(v, n) function.
- Parameters:
v- Input vectorn- Number of positions to return- Returns:
Array of indices of n smallest values (0-based), sorted by value (ascending)
-
randomMatlabStyle
static boolean randomMatlabStyle()
-
setMatlabRandomSeed
static void setMatlabRandomSeed(long seed)
-
setRandomNumbersMatlab
static void setRandomNumbersMatlab(boolean matlab_style)
-
simplex_fun
static double simplex_fun(Array<double> x, Matrix L, Matrix N)
Computes a specialized function used in simplex-based optimization algorithms. This function evaluates an exponential transformation of the input variables combined with matrix operations involving L and N matrices.
The function performs the following computation:
- Creates a vector v where v[i] = exp(x[i]) for i = 0..M-2, and v[M-1] = 1
- Computes tmp = log(v * L)^T (element-wise logarithm of matrix product)
- Returns exp(N * tmp + sum(x) - (sum(N) + M) * log(sum(v)))
This function is typically used in optimization contexts where the variables are constrained to a simplex and require exponential parameterization.
- Parameters:
x- The input vector of optimization variables (length M-1)L- The transformation matrix for the exponential variablesN- The weighting vector for the final computation- Returns:
The computed function value as a double
-
simplexquad
static Maths.simplexQuadResult simplexquad(Function<Array<double>, Double> f, int n, int order, double tol)
-
softmin
static double softmin(double x, double y, double alpha)
Softmin function.
- Parameters:
x- first term to comparey- second term to comparealpha- softmin smoothing parameter- Returns:
Softmin function value
-
transpose
static Array<Array<double>> transpose(Array<Array<double>> data)
Transposes a 2D array of values.
- Parameters:
data- 2D array to be transposed.- Returns:
New 2D array of transposed data.
-
uniqueAndSort
static Matrix uniqueAndSort(Matrix space)
-
uniquePerms
static Matrix uniquePerms(Matrix vec)
-
setdiff
static Matrix setdiff(Matrix A, Matrix B)
Set difference operation for Matrix objects that are vectors. Returns elements in A that are not in B.
- Parameters:
A- First vector (universe of values to check)B- Second vector (values to exclude from A)- Returns:
Matrix containing elements in A that are not in B, or empty matrix if inputs are invalid
-
multichoose
static Matrix multichoose(int n, int k)
Generates all combinations of n objects taken k at a time with repetition (multichoose). Returns a Matrix for compatibility with existing code.
- Parameters:
n- number of distinct objectsk- total number of selections- Returns:
Matrix where each row is a combination
-
multichooseList
static List<Array<int>> multichooseList(int n, int k)
Generates all combinations of n objects taken k at a time with repetition (multichoose). Each combination is an array where element i represents how many times object i is chosen.
- Parameters:
n- number of distinct objectsk- total number of selections- Returns:
list of combinations as int arrays
-
sortByNnzPos
static List<Array<int>> sortByNnzPos(List<Array<int>> combinations)
Sorts combinations by number of non-zeros and their positions.
- Parameters:
combinations- list of combinations to sort- Returns:
sorted list of combinations
-
nnzcmp
static int nnzcmp(Array<int> i1, Array<int> i2)
Compares two arrays by number of zeros and their positions. Returns 1 if a <b, -1 if a >b, 0 if equal.
- Parameters:
i1- first arrayi2- second array- Returns:
comparison result
-
matchRow
static int matchRow(List<Array<int>> rows, Array<int> target)
Finds the index of a matching row in a list.
- Parameters:
rows- list of integer arraystarget- array to find- Returns:
index of matching row, or -1 if not found
-
nchoosek
static int nchoosek(int n, int k)
Computes binomial coefficient "n choose k".
- Parameters:
n- total itemsk- items chosen- Returns:
binomial coefficient
-
goldenSectionSearch
static Array<double> goldenSectionSearch(Function<Double, Double> function, double a, double b, double tol)
Golden section search for finding the minimum of a unimodal function. This is equivalent to Python's scipy.optimize.fminbound method.
- Parameters:
function- The function to minimizea- Lower bound of search intervalb- Upper bound of search intervaltol- Tolerance for convergence (default: 1e-5)- Returns:
Array containing [optimal_x, optimal_value]
-
goldenSectionSearch
static Array<double> goldenSectionSearch(Function<Double, Double> function, double a, double b)
Golden section search with default tolerance.
- Parameters:
function- The function to minimizea- Lower bound of search intervalb- Upper bound of search interval- Returns:
Array containing [optimal_x, optimal_value]
-
-
-
-