Package jline.util

Class Maths

java.lang.Object
jline.util.Maths

public class Maths extends Object
Mathematical functions and utilities.
  • 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 items
      k - items chosen
      Returns:
      the binomial coefficient, or 0.0 if k<0 or k>n
    • circul

      public 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

      public 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

      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

      public 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.

      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

      public static Matrix binHist(Matrix v, int minVal, int maxVal)
      Implementation of MATLAB "hist": puts elements of v into k bins
      Parameters:
      v - - vector of elements
      minVal - - lowest number in v
      maxVal - - 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 items
      k - items chosen
      Returns:
      log of the binomial coefficient, or NegInf if k<0 or k>n
    • logmeanexp

      public static double logmeanexp(Matrix x)
    • 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 compared
      y - - 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 compared
      y - - the second number to be compared
      Returns:
      - the min between the two
    • multiChooseCombinations

      public static List<Matrix> multiChooseCombinations(int k, int n)
      Generate all combinations of distributing n items into k bins
    • multiChooseCon

      public static Matrix multiChooseCon(Matrix n, double S)
    • multichoose

      public static Matrix multichoose(double n, double k)
    • multichoosecon

      public static Matrix multichoosecon(Matrix n, int S)
      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 vector
      S - number of units to pick
      Returns:
      one row per admissible pick
    • multinomialln

      public static double multinomialln(Matrix n)
    • nCk

      public static double nCk(double n, double k)
    • nCk

      public static Matrix nCk(Matrix v, int k)
      Computes the combinations of the elements in v taken k at a time
      Parameters:
      v - - vector of elements
      k - - 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

      public static Matrix num_grad_h(Matrix x0, double h, SerializableFunction<Matrix,Matrix> hfun)
    • num_grad_h_complex

      public static ComplexMatrix num_grad_h_complex(Matrix x0, double h, SerializableFunction<Matrix,ComplexMatrix> hfun)
    • num_hess_h

      public static Matrix num_hess_h(Matrix x0, double h, SerializableFunction<Matrix,Matrix> hfun)
    • num_hess_h_complex

      public static ComplexMatrix num_hess_h_complex(Matrix x0, double h, SerializableFunction<Matrix,ComplexMatrix> hfun)
    • permutations

      public static Matrix permutations(Matrix vec)
    • rand

      public static double rand()
    • randn

      public static double randn()
    • probchoose

      public 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.0)
      Returns:
      Index of chosen element (0-based)
    • probchoose

      public 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

      public 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

      public static 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 vector
      n - Number of positions to return
      Returns:
      Array of indices of n largest values (0-based), sorted by value (descending)
    • minpos

      public 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

      public static 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 vector
      n - 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

      public static org.apache.commons.math3.complex.Complex[] roots(Matrix coefficients)
    • 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

      public static double simplex_fun(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:

      1. Creates a vector v where v[i] = exp(x[i]) for i = 0..M-2, and v[M-1] = 1
      2. Computes tmp = log(v * L)^T (element-wise logarithm of matrix product)
      3. 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 variables
      N - The weighting vector for the final computation
      Returns:
      The computed function value as a double
      Throws:
      IllegalArgumentException - if matrix dimensions are incompatible
    • simplex_logfun

      public static double simplex_logfun(double[] x, Matrix L, Matrix N)
      Log-domain form of simplex_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 compare
      y - second term to compare
      alpha - softmin smoothing parameter
      Returns:
      Softmin function value
    • sub2ind

      public static List<Integer> sub2ind(Matrix dims, Matrix row, Matrix col)
    • 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

      public static Matrix uniqueAndSort(Matrix space)
    • multisetPerms

      public static Matrix multisetPerms(Matrix vec)
      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 in FromMarginal, 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 through permutations(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 twin matlab/util/multiset_perms.m produces, and the python (api/state/multiset_perms.py) and C++ (pas_multiset_perms in lang/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 ascending unique because every caller assembles the vector in ascending class order. Replaced the transliterated uniqueperms.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

      public 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

      public 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 objects
      k - total number of selections
      Returns:
      Matrix where each row is a combination
    • multichooseList

      public static List<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 objects
      k - total number of selections
      Returns:
      list of combinations as int arrays
    • sortByNnzPos

      public static List<int[]> sortByNnzPos(List<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

      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 array
      i2 - second array
      Returns:
      comparison result
    • matchRow

      public static int matchRow(List<int[]> rows, int[] target)
      Finds the index of a matching row in a list.
      Parameters:
      rows - list of integer arrays
      target - 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 items
      k - 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 minimize
      a - Lower bound of search interval
      b - Upper bound of search interval
      tol - Tolerance for convergence (default: 1e-5)
      Returns:
      Array containing [optimal_x, optimal_value]
    • goldenSectionSearch

      public static double[] goldenSectionSearch(Function<Double,Double> function, double a, double b)
      Golden section search with default tolerance.
      Parameters:
      function - The function to minimize
      a - Lower bound of search interval
      b - Upper bound of search interval
      Returns:
      Array containing [optimal_x, optimal_value]