Package jline.util
Class Maths
java.lang.Object
jline.util.Maths
Mathematical functions and utilities.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classstatic classstatic class -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic MatrixImplementation of MATLAB "hist": puts elements of v into k binsstatic 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 MatrixReturns a circulant matrix from the given first column.static double[]cumSum(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 int[]cumSum(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 voidelementAdd(int[] ar, int i) Helper method that adds an integer to every element of an integer array.static doublefact(double n) Computes the factorial of a double value using the gamma function.static intfact(int n) Computes the factorial of an integer.static doublefactln(double n) Computes the natural logarithm of the factorial for a double value.static doublefactln(int n) Computes the natural logarithm of the factorial.static doublegammaFunction(double x) Computes the gamma function via Lanczos approximation formula.static double[]goldenSectionSearch(Function<Double, Double> function, double a, double b) Golden section search with default tolerance.static double[]goldenSectionSearch(Function<Double, Double> function, double a, double b, double tol) Golden section search for finding the minimum of a unimodal function.static Maths.simplexQuadResultGrundmann-Moeller simplex integrationstatic Maths.laplaceApproxReturnstatic 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 double[]logSpace(double min, double max, int n) static int[]logSpacei(int start, int stop, int n) Generates an integer list of n logarithmically spaced values.static intFinds the index of a matching row in a list.static MatrixAdapted from jblas and IHMC Original documentation:static doublemax(double x, double y) Returns the max of two numbers.static intReturns the position of the maximum value in a vector.static int[]Returns the positions of the n largest values in a vector.static doublemin(double x, double y) Returns the min of two numbers.static intReturns the position of the minimum value in a vector.static int[]Returns the positions of the n smallest values in a vector.static Matrixmultichoose(double n, double k) static Matrixmultichoose(int n, int k) Generates all combinations of n objects taken k at a time with repetition (multichoose).multiChooseCombinations(int k, int n) Generate all combinations of distributing n items into k binsstatic Matrixmultichoosecon(Matrix n, int S) Pick vectors of S units from the units available in vector n.static MatrixmultiChooseCon(Matrix n, double S) static List<int[]>multichooseList(int n, int k) Generates all combinations of n objects taken k at a time with repetition (multichoose).static doublestatic MatrixmultisetPerms(Matrix vec) All distinct permutations of the multiset held in a row vector, one per row.static intnchoosek(int n, int k) Computes binomial coefficient "n choose k".static doublenCk(double n, double k) static MatrixComputes the combinations of the elements in v taken k at a timeprotected 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 intnnzcmp(int[] i1, int[] i2) Compares two arrays by number of zeros and their positions.static doublenormalErf(double x) Computes the error function (erf) of a value.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 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 doublerand()static doublerandn()static booleanstatic org.apache.commons.math3.complex.Complex[]roots(double[] coefficients) static org.apache.commons.math3.complex.Complex[]static MatrixSet difference operation for Matrix objects that are vectors.static voidsetMatlabRandomSeed(long seed) static voidsetRandomNumbersMatlab(boolean matlab_style) static doublesimplex_fun(double[] x, Matrix L, Matrix N) Computes a specialized function used in simplex-based optimization algorithms.static doublesimplex_logfun(double[] x, Matrix L, Matrix N) Log-domain form ofsimplex_fun(double[], jline.util.matrix.Matrix, jline.util.matrix.Matrix): returns the exponent, i.e.static Maths.simplexQuadResultsimplexquad(Function<double[], Double> f, int n, int order, double tol) static doublesoftmin(double x, double y, double alpha) Softmin function, a smooth approximation of min(x,y).static List<int[]>sortByNnzPos(List<int[]> combinations) Sorts combinations by number of non-zeros and their positions.static double[][]transpose(double[][] data) Transposes a 2D array of values.static MatrixuniqueAndSort(Matrix space)
-
Constructor Details
-
Maths
public Maths()
-
-
Method Details
-
binomialCoeff
public 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
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
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
public static int[] cumSum(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
public static double[] cumSum(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
public static void elementAdd(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
public 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
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.
- Parameters:
matrix-- Returns:
- matrix exponential of the matrix
-
fact
public static int fact(int n) Computes the factorial of an integer.- Parameters:
n- the input value- Returns:
- n! (n factorial)
-
fact
public 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
public static double factln(int n) Computes the natural logarithm of the factorial.- Parameters:
n- the input value- Returns:
- ln(n!)
-
factln
public 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
public 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
public static Maths.simplexQuadResult grnmol(Function<double[], Double> f, double[][] V, int s, double tol) Grundmann-Moeller simplex integration -
binHist
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
public static Maths.laplaceApproxReturn laplaceapprox_h(Matrix x0, SerializableFunction<Matrix, Matrix> h) -
laplaceapprox_h_complex
public static Maths.laplaceApproxComplexReturn laplaceapprox_h_complex(Matrix x0, SerializableFunction<Matrix, ComplexMatrix> h) -
linSpace
public static double[] linSpace(double start, double end, int num) -
logBinomial
public 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
-
logSpace
public static double[] logSpace(double min, double max, int n) -
logSpacei
public static 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
public 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
public 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
Generate all combinations of distributing n items into k bins -
multiChooseCon
-
multichoose
-
multichoosecon
Pick vectors of S units from the units available in vector n.Twin of the MATLAB util multichoosecon.m. Unlike multichoose, which enumerates every composition of S, this one is bounded above by n entrywise, which is what "choose S of the jobs actually present" means. S = 0 has the single all-zero answer.
- Parameters:
n- available units per bin, as a row vectorS- number of units to pick- Returns:
- one row per admissible pick
-
multinomialln
-
nCk
public static double nCk(double n, double k) -
nCk
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
protected 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
-
num_grad_h_complex
public static ComplexMatrix num_grad_h_complex(Matrix x0, double h, SerializableFunction<Matrix, ComplexMatrix> hfun) -
num_hess_h
-
num_hess_h_complex
public static ComplexMatrix num_hess_h_complex(Matrix x0, double h, SerializableFunction<Matrix, ComplexMatrix> hfun) -
permutations
-
rand
public static double rand() -
randn
public static double randn() -
probchoose
Choose an element index according to probability vector. Equivalent to MATLAB's probchoose function.- Parameters:
p- Probability vector (must sum to 1.0)- Returns:
- Index of chosen element (0-based)
-
probchoose
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
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
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
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
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
public static boolean randomMatlabStyle() -
roots
-
roots
public static org.apache.commons.math3.complex.Complex[] roots(double[] coefficients) -
setMatlabRandomSeed
public static void setMatlabRandomSeed(long seed) -
setRandomNumbersMatlab
public static void setRandomNumbersMatlab(boolean matlab_style) -
simplex_fun
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
- Throws:
IllegalArgumentException- if matrix dimensions are incompatible
-
simplex_logfun
Log-domain form ofsimplex_fun(double[], jline.util.matrix.Matrix, jline.util.matrix.Matrix): returns the exponent, i.e. log(simplex_fun), without exponentiating. Kept in the log domain so the integrand does not overflow for models with large normalizing constants. -
simplexquad
public static Maths.simplexQuadResult simplexquad(Function<double[], Double> f, int n, int order, double tol) -
softmin
public static double softmin(double x, double y, double alpha) Softmin function, a smooth approximation of min(x,y). The literal weighted-average form (x*exp(-alpha*x) + y*exp(-alpha*y)) / (exp(-alpha*x) + exp(-alpha*y)) overflows once alpha*|x| leaves the double range and then evaluates Inf*0 = NaN. With lo = min(x,y), gap = |x-y| and w = exp(-alpha*gap) the algebraically identical form (lo + hi*w)/(1 + w) = lo + gap*w/(1 + w) keeps the exponent argument non-positive, so w stays in (0,1] and the limit w -> 0 returns min(x,y) exactly.- Parameters:
x- first term to comparey- second term to comparealpha- softmin smoothing parameter- Returns:
- Softmin function value
-
sub2ind
-
transpose
public static double[][] transpose(double[][] data) Transposes a 2D array of values.- Parameters:
data- 2D array to be transposed.- Returns:
- New 2D array of transposed data.
-
uniqueAndSort
-
multisetPerms
All distinct permutations of the multiset held in a row vector, one per row. ROW ORDER IS PART OF THE CONTRACT, not an implementation detail: these rows become the local state space inFromMarginal, whose first row (after the reversal the builders apply) is the default initial state, so reordering them moves which state a chain starts in. Two orders are produced and which applies depends on the vector: an all-distinct vector goes throughpermutations(jline.util.matrix.Matrix), which lists REVERSE lexicographically, while a vector with a repeat is grouped by leading value and recurses on the remainder. The mixture is the one the MATLAB twinmatlab/util/multiset_perms.mproduces, and the python (api/state/multiset_perms.py) and C++ (pas_multiset_permsinlang/qn/state.h) twins reproduce it too. Distinct values are taken in FIRST-APPEARANCE order rather than sorted. That is what this has always done, and it agrees with MATLAB's ascendinguniquebecause every caller assembles the vector in ascending class order. Replaced the transliterateduniqueperms.m(J. D'Errico) on 2026-08-19: the vendored original carried an author byline but no license grant. This is written from the enumeration rule above rather than from that source, and it collects the recursive blocks before allocating instead of growing the result by a full copy per block.- Parameters:
vec- a single-row Matrix, repeats allowed- Returns:
- one row per distinct permutation; an empty 0x0 Matrix for empty input
-
setdiff
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
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
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
Sorts combinations by number of non-zeros and their positions.- Parameters:
combinations- list of combinations to sort- Returns:
- sorted list of combinations
-
nnzcmp
public static int nnzcmp(int[] i1, 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
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
public static int nchoosek(int n, int k) Computes binomial coefficient "n choose k".- Parameters:
n- total itemsk- items chosen- Returns:
- binomial coefficient
-
goldenSectionSearch
public static 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
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]
-