feat:node-modules

This commit is contained in:
houjunxiang
2025-11-24 10:26:18 +08:00
parent 753766893b
commit 8a3e48d856
8825 changed files with 567399 additions and 1 deletions

View File

@@ -0,0 +1,69 @@
import { factory } from '../../utils/factory.js';
import { combinationsNumber } from '../../plain/number/combinations.js';
var name = 'combinations';
var dependencies = ['typed'];
export var createCombinations = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Compute the number of ways of picking `k` unordered outcomes from `n`
* possibilities.
*
* Combinations only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.combinations(n, k)
*
* Examples:
*
* math.combinations(7, 5) // returns 21
*
* See also:
*
* combinationsWithRep, permutations, factorial
*
* @param {number | BigNumber} n Total number of objects in the set
* @param {number | BigNumber} k Number of objects in the subset
* @return {number | BigNumber} Number of possible combinations.
*/
return typed(name, {
'number, number': combinationsNumber,
'BigNumber, BigNumber': function BigNumber_BigNumber(n, k) {
var BigNumber = n.constructor;
var result, i;
var nMinusk = n.minus(k);
var one = new BigNumber(1);
if (!isPositiveInteger(n) || !isPositiveInteger(k)) {
throw new TypeError('Positive integer value expected in function combinations');
}
if (k.gt(n)) {
throw new TypeError('k must be less than n in function combinations');
}
result = one;
if (k.lt(nMinusk)) {
for (i = one; i.lte(nMinusk); i = i.plus(one)) {
result = result.times(k.plus(i)).dividedBy(i);
}
} else {
for (i = one; i.lte(k); i = i.plus(one)) {
result = result.times(nMinusk.plus(i)).dividedBy(i);
}
}
return result;
}
// TODO: implement support for collection in combinations
});
});
/**
* Test whether BigNumber n is a positive integer
* @param {BigNumber} n
* @returns {boolean} isPositiveInteger
*/
function isPositiveInteger(n) {
return n.isInteger() && n.gte(0);
}

View File

@@ -0,0 +1,84 @@
import { factory } from '../../utils/factory.js';
import { isInteger } from '../../utils/number.js';
import { product } from '../../utils/product.js';
var name = 'combinationsWithRep';
var dependencies = ['typed'];
export var createCombinationsWithRep = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Compute the number of ways of picking `k` unordered outcomes from `n`
* possibilities, allowing individual outcomes to be repeated more than once.
*
* CombinationsWithRep only takes integer arguments.
* The following condition must be enforced: k <= n + k -1.
*
* Syntax:
*
* math.combinationsWithRep(n, k)
*
* Examples:
*
* math.combinationsWithRep(7, 5) // returns 462
*
* See also:
*
* combinations, permutations, factorial
*
* @param {number | BigNumber} n Total number of objects in the set
* @param {number | BigNumber} k Number of objects in the subset
* @return {number | BigNumber} Number of possible combinations with replacement.
*/
return typed(name, {
'number, number': function number_number(n, k) {
if (!isInteger(n) || n < 0) {
throw new TypeError('Positive integer value expected in function combinationsWithRep');
}
if (!isInteger(k) || k < 0) {
throw new TypeError('Positive integer value expected in function combinationsWithRep');
}
if (n < 1) {
throw new TypeError('k must be less than or equal to n + k - 1');
}
if (k < n - 1) {
var _prodrange = product(n, n + k - 1);
return _prodrange / product(1, k);
}
var prodrange = product(k + 1, n + k - 1);
return prodrange / product(1, n - 1);
},
'BigNumber, BigNumber': function BigNumber_BigNumber(n, k) {
var BigNumber = n.constructor;
var result, i;
var one = new BigNumber(1);
var nMinusOne = n.minus(one);
if (!isPositiveInteger(n) || !isPositiveInteger(k)) {
throw new TypeError('Positive integer value expected in function combinationsWithRep');
}
if (n.lt(one)) {
throw new TypeError('k must be less than or equal to n + k - 1 in function combinationsWithRep');
}
result = one;
if (k.lt(nMinusOne)) {
for (i = one; i.lte(nMinusOne); i = i.plus(one)) {
result = result.times(k.plus(i)).dividedBy(i);
}
} else {
for (i = one; i.lte(k); i = i.plus(one)) {
result = result.times(nMinusOne.plus(i)).dividedBy(i);
}
}
return result;
}
});
});
/**
* Test whether BigNumber n is a positive integer
* @param {BigNumber} n
* @returns {boolean} isPositiveInteger
*/
function isPositiveInteger(n) {
return n.isInteger() && n.gte(0);
}

View File

@@ -0,0 +1,47 @@
import { deepMap } from '../../utils/collection.js';
import { factory } from '../../utils/factory.js';
var name = 'factorial';
var dependencies = ['typed', 'gamma'];
export var createFactorial = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
gamma
} = _ref;
/**
* Compute the factorial of a value
*
* Factorial only supports an integer value as argument.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.factorial(n)
*
* Examples:
*
* math.factorial(5) // returns 120
* math.factorial(3) // returns 6
*
* See also:
*
* combinations, combinationsWithRep, gamma, permutations
*
* @param {number | BigNumber | Array | Matrix} n An integer number
* @return {number | BigNumber | Array | Matrix} The factorial of `n`
*/
return typed(name, {
number: function number(n) {
if (n < 0) {
throw new Error('Value must be non-negative');
}
return gamma(n + 1);
},
BigNumber: function BigNumber(n) {
if (n.isNegative()) {
throw new Error('Value must be non-negative');
}
return gamma(n.plus(1));
},
'Array | Matrix': typed.referToSelf(self => n => deepMap(n, self))
});
});

View File

@@ -0,0 +1,120 @@
import { factory } from '../../utils/factory.js';
import { gammaG, gammaNumber, gammaP } from '../../plain/number/index.js';
var name = 'gamma';
var dependencies = ['typed', 'config', 'multiplyScalar', 'pow', 'BigNumber', 'Complex'];
export var createGamma = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
multiplyScalar,
pow,
BigNumber: _BigNumber,
Complex
} = _ref;
/**
* Compute the gamma function of a value using Lanczos approximation for
* small values, and an extended Stirling approximation for large values.
*
* To avoid confusion with the matrix Gamma function, this function does
* not apply to matrices.
*
* Syntax:
*
* math.gamma(n)
*
* Examples:
*
* math.gamma(5) // returns 24
* math.gamma(-0.5) // returns -3.5449077018110335
* math.gamma(math.i) // returns -0.15494982830180973 - 0.49801566811835596i
*
* See also:
*
* combinations, factorial, permutations
*
* @param {number | BigNumber | Complex} n A real or complex number
* @return {number | BigNumber | Complex} The gamma of `n`
*/
function gammaComplex(n) {
if (n.im === 0) {
return gammaNumber(n.re);
}
// Lanczos approximation doesn't work well with real part lower than 0.5
// So reflection formula is required
if (n.re < 0.5) {
// Euler's reflection formula
// gamma(1-z) * gamma(z) = PI / sin(PI * z)
// real part of Z should not be integer [sin(PI) == 0 -> 1/0 - undefined]
// thanks to imperfect sin implementation sin(PI * n) != 0
// we can safely use it anyway
var _t = new Complex(1 - n.re, -n.im);
var r = new Complex(Math.PI * n.re, Math.PI * n.im);
return new Complex(Math.PI).div(r.sin()).div(gammaComplex(_t));
}
// Lanczos approximation
// z -= 1
n = new Complex(n.re - 1, n.im);
// x = gammaPval[0]
var x = new Complex(gammaP[0], 0);
// for (i, gammaPval) in enumerate(gammaP):
for (var i = 1; i < gammaP.length; ++i) {
// x += gammaPval / (z + i)
var gammaPval = new Complex(gammaP[i], 0);
x = x.add(gammaPval.div(n.add(i)));
}
// t = z + gammaG + 0.5
var t = new Complex(n.re + gammaG + 0.5, n.im);
// y = sqrt(2 * pi) * t ** (z + 0.5) * exp(-t) * x
var twoPiSqrt = Math.sqrt(2 * Math.PI);
var tpow = t.pow(n.add(0.5));
var expt = t.neg().exp();
// y = [x] * [sqrt(2 * pi)] * [t ** (z + 0.5)] * [exp(-t)]
return x.mul(twoPiSqrt).mul(tpow).mul(expt);
}
return typed(name, {
number: gammaNumber,
Complex: gammaComplex,
BigNumber: function BigNumber(n) {
if (n.isInteger()) {
return n.isNegative() || n.isZero() ? new _BigNumber(Infinity) : bigFactorial(n.minus(1));
}
if (!n.isFinite()) {
return new _BigNumber(n.isNegative() ? NaN : Infinity);
}
throw new Error('Integer BigNumber expected');
}
});
/**
* Calculate factorial for a BigNumber
* @param {BigNumber} n
* @returns {BigNumber} Returns the factorial of n
*/
function bigFactorial(n) {
if (n < 8) {
return new _BigNumber([1, 1, 2, 6, 24, 120, 720, 5040][n]);
}
var precision = config.precision + (Math.log(n.toNumber()) | 0);
var Big = _BigNumber.clone({
precision
});
if (n % 2 === 1) {
return n.times(bigFactorial(new _BigNumber(n - 1)));
}
var p = n;
var prod = new Big(n);
var sum = n.toNumber();
while (p > 2) {
p -= 2;
sum += p;
prod = prod.times(sum);
}
return new _BigNumber(prod.toPrecision(_BigNumber.precision));
}
});

View File

@@ -0,0 +1,77 @@
import { factory } from '../../utils/factory.js';
var name = 'kldivergence';
var dependencies = ['typed', 'matrix', 'divide', 'sum', 'multiply', 'map', 'dotDivide', 'log', 'isNumeric'];
export var createKldivergence = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
divide,
sum,
multiply,
map,
dotDivide,
log,
isNumeric
} = _ref;
/**
* Calculate the Kullback-Leibler (KL) divergence between two distributions
*
* Syntax:
*
* math.kldivergence(x, y)
*
* Examples:
*
* math.kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5]) //returns 0.24376698773121153
*
*
* @param {Array | Matrix} q First vector
* @param {Array | Matrix} p Second vector
* @return {number} Returns distance between q and p
*/
return typed(name, {
'Array, Array': function Array_Array(q, p) {
return _kldiv(matrix(q), matrix(p));
},
'Matrix, Array': function Matrix_Array(q, p) {
return _kldiv(q, matrix(p));
},
'Array, Matrix': function Array_Matrix(q, p) {
return _kldiv(matrix(q), p);
},
'Matrix, Matrix': function Matrix_Matrix(q, p) {
return _kldiv(q, p);
}
});
function _kldiv(q, p) {
var plength = p.size().length;
var qlength = q.size().length;
if (plength > 1) {
throw new Error('first object must be one dimensional');
}
if (qlength > 1) {
throw new Error('second object must be one dimensional');
}
if (plength !== qlength) {
throw new Error('Length of two vectors must be equal');
}
// Before calculation, apply normalization
var sumq = sum(q);
if (sumq === 0) {
throw new Error('Sum of elements in first object must be non zero');
}
var sump = sum(p);
if (sump === 0) {
throw new Error('Sum of elements in second object must be non zero');
}
var qnorm = divide(q, sum(q));
var pnorm = divide(p, sum(p));
var result = sum(multiply(qnorm, map(dotDivide(qnorm, pnorm), x => log(x))));
if (isNumeric(result)) {
return result;
} else {
return Number.NaN;
}
}
});

View File

@@ -0,0 +1,137 @@
/* eslint-disable no-loss-of-precision */
// References
// ----------
// [1] Hare, "Computing the Principal Branch of log-Gamma", Journal of Algorithms, 1997.
// [2] https://math.stackexchange.com/questions/1338753/how-do-i-calculate-values-for-gamma-function-with-complex-arguments
import { lgammaNumber, lnSqrt2PI } from '../../plain/number/index.js';
import { factory } from '../../utils/factory.js';
import { copysign } from '../../utils/number.js';
var name = 'lgamma';
var dependencies = ['Complex', 'typed'];
export var createLgamma = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
Complex,
typed
} = _ref;
// Stirling series is non-convergent, we need to use the recurrence `lgamma(z) = lgamma(z+1) - log z` to get
// sufficient accuracy.
//
// These two values are copied from Scipy implementation:
// https://github.com/scipy/scipy/blob/v1.8.0/scipy/special/_loggamma.pxd#L37
var SMALL_RE = 7;
var SMALL_IM = 7;
/**
* The coefficients are B[2*n]/(2*n*(2*n - 1)) where B[2*n] is the (2*n)th Bernoulli number. See (1.1) in [1].
*
* If you cannot access the paper, can also get these values from the formula in [2].
*
* 1 / 12 = 0.00833333333333333333333333333333
* 1 / 360 = 0.00277777777777777777777777777778
* ...
* 3617 / 133400 = 0.02955065359477124183006535947712
*/
var coeffs = [-2.955065359477124183e-2, 6.4102564102564102564e-3, -1.9175269175269175269e-3, 8.4175084175084175084e-4, -5.952380952380952381e-4, 7.9365079365079365079e-4, -2.7777777777777777778e-3, 8.3333333333333333333e-2];
/**
* Logarithm of the gamma function for real, positive numbers and complex numbers,
* using Lanczos approximation for numbers and Stirling series for complex numbers.
*
* Syntax:
*
* math.lgamma(n)
*
* Examples:
*
* math.lgamma(5) // returns 3.178053830347945
* math.lgamma(0) // returns Infinity
* math.lgamma(-0.5) // returns NaN
* math.lgamma(math.i) // returns -0.6509231993018536 - 1.8724366472624294i
*
* See also:
*
* gamma
*
* @param {number | Complex} n A real or complex number
* @return {number | Complex} The log gamma of `n`
*/
return typed(name, {
number: lgammaNumber,
Complex: lgammaComplex,
BigNumber: function BigNumber() {
throw new Error("mathjs doesn't yet provide an implementation of the algorithm lgamma for BigNumber");
}
});
function lgammaComplex(n) {
var TWOPI = 6.2831853071795864769252842; // 2*pi
var LOGPI = 1.1447298858494001741434262; // log(pi)
var REFLECTION = 0.1;
if (n.isNaN()) {
return new Complex(NaN, NaN);
} else if (n.im === 0) {
return new Complex(lgammaNumber(n.re), 0);
} else if (n.re >= SMALL_RE || Math.abs(n.im) >= SMALL_IM) {
return lgammaStirling(n);
} else if (n.re <= REFLECTION) {
// Reflection formula. see Proposition 3.1 in [1]
var tmp = copysign(TWOPI, n.im) * Math.floor(0.5 * n.re + 0.25);
var a = n.mul(Math.PI).sin().log();
var b = lgammaComplex(new Complex(1 - n.re, -n.im));
return new Complex(LOGPI, tmp).sub(a).sub(b);
} else if (n.im >= 0) {
return lgammaRecurrence(n);
} else {
return lgammaRecurrence(n.conjugate()).conjugate();
}
}
function lgammaStirling(z) {
// formula ref in [2]
// computation ref:
// https://github.com/scipy/scipy/blob/v1.8.0/scipy/special/_loggamma.pxd#L101
// left part
// x (log(x) - 1) + 1/2 (log(2PI) - log(x))
// => (x - 0.5) * log(x) - x + log(2PI) / 2
var leftPart = z.sub(0.5).mul(z.log()).sub(z).add(lnSqrt2PI);
// right part
var rz = new Complex(1, 0).div(z);
var rzz = rz.div(z);
var a = coeffs[0];
var b = coeffs[1];
var r = 2 * rzz.re;
var s = rzz.re * rzz.re + rzz.im * rzz.im;
for (var i = 2; i < 8; i++) {
var tmp = b;
b = -s * a + coeffs[i];
a = r * a + tmp;
}
var rightPart = rz.mul(rzz.mul(a).add(b));
// plus left and right
return leftPart.add(rightPart);
}
function lgammaRecurrence(z) {
// computation ref:
// https://github.com/scipy/scipy/blob/v1.8.0/scipy/special/_loggamma.pxd#L78
var signflips = 0;
var sb = 0;
var shiftprod = z;
z = z.add(1);
while (z.re <= SMALL_RE) {
shiftprod = shiftprod.mul(z);
var nsb = shiftprod.im < 0 ? 1 : 0;
if (nsb !== 0 && sb === 0) signflips++;
sb = nsb;
z = z.add(1);
}
return lgammaStirling(z).sub(shiftprod.log()).sub(new Complex(0, signflips * 2 * Math.PI * 1));
}
});

View File

@@ -0,0 +1,50 @@
import { deepForEach } from '../../utils/collection.js';
import { factory } from '../../utils/factory.js';
var name = 'multinomial';
var dependencies = ['typed', 'add', 'divide', 'multiply', 'factorial', 'isInteger', 'isPositive'];
export var createMultinomial = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
add,
divide,
multiply,
factorial,
isInteger,
isPositive
} = _ref;
/**
* Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities.
*
* multinomial takes one array of integers as an argument.
* The following condition must be enforced: every ai <= 0
*
* Syntax:
*
* math.multinomial(a) // a is an array type
*
* Examples:
*
* math.multinomial([1,2,1]) // returns 12
*
* See also:
*
* combinations, factorial
*
* @param {number[] | BigNumber[]} a Integer numbers of objects in the subset
* @return {Number | BigNumber} Multinomial coefficient.
*/
return typed(name, {
'Array | Matrix': function Array__Matrix(a) {
var sum = 0;
var denom = 1;
deepForEach(a, function (ai) {
if (!isInteger(ai) || !isPositive(ai)) {
throw new TypeError('Positive integer value expected in function multinomial');
}
sum = add(sum, ai);
denom = multiply(denom, factorial(ai));
});
return divide(factorial(sum), denom);
}
});
});

View File

@@ -0,0 +1,78 @@
import { isInteger } from '../../utils/number.js';
import { product } from '../../utils/product.js';
import { factory } from '../../utils/factory.js';
var name = 'permutations';
var dependencies = ['typed', 'factorial'];
export var createPermutations = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
factorial
} = _ref;
/**
* Compute the number of ways of obtaining an ordered subset of `k` elements
* from a set of `n` elements.
*
* Permutations only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.permutations(n)
* math.permutations(n, k)
*
* Examples:
*
* math.permutations(5) // 120
* math.permutations(5, 3) // 60
*
* See also:
*
* combinations, combinationsWithRep, factorial
*
* @param {number | BigNumber} n The number of objects in total
* @param {number | BigNumber} [k] The number of objects in the subset
* @return {number | BigNumber} The number of permutations
*/
return typed(name, {
'number | BigNumber': factorial,
'number, number': function number_number(n, k) {
if (!isInteger(n) || n < 0) {
throw new TypeError('Positive integer value expected in function permutations');
}
if (!isInteger(k) || k < 0) {
throw new TypeError('Positive integer value expected in function permutations');
}
if (k > n) {
throw new TypeError('second argument k must be less than or equal to first argument n');
}
// Permute n objects, k at a time
return product(n - k + 1, n);
},
'BigNumber, BigNumber': function BigNumber_BigNumber(n, k) {
var result, i;
if (!isPositiveInteger(n) || !isPositiveInteger(k)) {
throw new TypeError('Positive integer value expected in function permutations');
}
if (k.gt(n)) {
throw new TypeError('second argument k must be less than or equal to first argument n');
}
var one = n.mul(0).add(1);
result = one;
for (i = n.minus(k).plus(1); i.lte(n); i = i.plus(1)) {
result = result.times(i);
}
return result;
}
// TODO: implement support for collection in permutations
});
});
/**
* Test whether BigNumber n is a positive integer
* @param {BigNumber} n
* @returns {boolean} isPositiveInteger
*/
function isPositiveInteger(n) {
return n.isInteger() && n.gte(0);
}

View File

@@ -0,0 +1,150 @@
import { flatten } from '../../utils/array.js';
import { factory } from '../../utils/factory.js';
import { isMatrix, isNumber } from '../../utils/is.js';
import { createRng } from './util/seededRNG.js';
var name = 'pickRandom';
var dependencies = ['typed', 'config', '?on'];
export var createPickRandom = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
on
} = _ref;
// seeded pseudo random number generator
var rng = createRng(config.randomSeed);
if (on) {
on('config', function (curr, prev) {
if (curr.randomSeed !== prev.randomSeed) {
rng = createRng(curr.randomSeed);
}
});
}
/**
* Random pick one or more values from a one dimensional array.
* Array elements are picked using a random function with uniform or weighted distribution.
*
* Syntax:
*
* math.pickRandom(array)
* math.pickRandom(array, number)
* math.pickRandom(array, weights)
* math.pickRandom(array, number, weights)
* math.pickRandom(array, weights, number)
* math.pickRandom(array, { weights, number, elementWise })
*
* Examples:
*
* math.pickRandom([3, 6, 12, 2]) // returns one of the values in the array
* math.pickRandom([3, 6, 12, 2], 2) // returns an array of two of the values in the array
* math.pickRandom([3, 6, 12, 2], { number: 2 }) // returns an array of two of the values in the array
* math.pickRandom([3, 6, 12, 2], [1, 3, 2, 1]) // returns one of the values in the array with weighted distribution
* math.pickRandom([3, 6, 12, 2], 2, [1, 3, 2, 1]) // returns an array of two of the values in the array with weighted distribution
* math.pickRandom([3, 6, 12, 2], [1, 3, 2, 1], 2) // returns an array of two of the values in the array with weighted distribution
*
* math.pickRandom([{x: 1.0, y: 2.0}, {x: 1.1, y: 2.0}], { elementWise: false })
* // returns one of the items in the array
*
* See also:
*
* random, randomInt
*
* @param {Array | Matrix} array A one dimensional array
* @param {Int} number An int or float
* @param {Array | Matrix} weights An array of ints or floats
* @return {number | Array} Returns a single random value from array when number is undefined.
* Returns an array with the configured number of elements when number is defined.
*/
return typed(name, {
'Array | Matrix': function Array__Matrix(possibles) {
return _pickRandom(possibles, {});
},
'Array | Matrix, Object': function Array__Matrix_Object(possibles, options) {
return _pickRandom(possibles, options);
},
'Array | Matrix, number': function Array__Matrix_number(possibles, number) {
return _pickRandom(possibles, {
number
});
},
'Array | Matrix, Array | Matrix': function Array__Matrix_Array__Matrix(possibles, weights) {
return _pickRandom(possibles, {
weights
});
},
'Array | Matrix, Array | Matrix, number': function Array__Matrix_Array__Matrix_number(possibles, weights, number) {
return _pickRandom(possibles, {
number,
weights
});
},
'Array | Matrix, number, Array | Matrix': function Array__Matrix_number_Array__Matrix(possibles, number, weights) {
return _pickRandom(possibles, {
number,
weights
});
}
});
/**
* @param {Array | Matrix} possibles
* @param {{
* number?: number,
* weights?: Array | Matrix,
* elementWise: boolean
* }} options
* @returns {number | Array}
* @private
*/
function _pickRandom(possibles, _ref2) {
var {
number,
weights,
elementWise = true
} = _ref2;
var single = typeof number === 'undefined';
if (single) {
number = 1;
}
var createMatrix = isMatrix(possibles) ? possibles.create : isMatrix(weights) ? weights.create : null;
possibles = possibles.valueOf(); // get Array
if (weights) {
weights = weights.valueOf(); // get Array
}
if (elementWise === true) {
possibles = flatten(possibles);
weights = flatten(weights);
}
var totalWeights = 0;
if (typeof weights !== 'undefined') {
if (weights.length !== possibles.length) {
throw new Error('Weights must have the same length as possibles');
}
for (var i = 0, len = weights.length; i < len; i++) {
if (!isNumber(weights[i]) || weights[i] < 0) {
throw new Error('Weights must be an array of positive numbers');
}
totalWeights += weights[i];
}
}
var length = possibles.length;
var result = [];
var pick;
while (result.length < number) {
if (typeof weights === 'undefined') {
pick = possibles[Math.floor(rng() * length)];
} else {
var randKey = rng() * totalWeights;
for (var _i = 0, _len = possibles.length; _i < _len; _i++) {
randKey -= weights[_i];
if (randKey < 0) {
pick = possibles[_i];
break;
}
}
}
result.push(pick);
}
return single ? result[0] : createMatrix ? createMatrix(result) : result;
}
});

View File

@@ -0,0 +1,96 @@
import { factory } from '../../utils/factory.js';
import { isMatrix } from '../../utils/is.js';
import { createRng } from './util/seededRNG.js';
import { randomMatrix } from './util/randomMatrix.js';
var name = 'random';
var dependencies = ['typed', 'config', '?on'];
export var createRandom = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
on
} = _ref;
// seeded pseudo random number generator
var rng = createRng(config.randomSeed);
if (on) {
on('config', function (curr, prev) {
if (curr.randomSeed !== prev.randomSeed) {
rng = createRng(curr.randomSeed);
}
});
}
/**
* Return a random number larger or equal to `min` and smaller than `max`
* using a uniform distribution.
*
* Syntax:
*
* math.random() // generate a random number between 0 and 1
* math.random(max) // generate a random number between 0 and max
* math.random(min, max) // generate a random number between min and max
* math.random(size) // generate a matrix with random numbers between 0 and 1
* math.random(size, max) // generate a matrix with random numbers between 0 and max
* math.random(size, min, max) // generate a matrix with random numbers between min and max
*
* Examples:
*
* math.random() // returns a random number between 0 and 1
* math.random(100) // returns a random number between 0 and 100
* math.random(30, 40) // returns a random number between 30 and 40
* math.random([2, 3]) // returns a 2x3 matrix with random numbers between 0 and 1
*
* See also:
*
* randomInt, pickRandom
*
* @param {Array | Matrix} [size] If provided, an array or matrix with given
* size and filled with random values is returned
* @param {number} [min] Minimum boundary for the random value, included
* @param {number} [max] Maximum boundary for the random value, excluded
* @return {number | Array | Matrix} A random number
*/
return typed(name, {
'': () => _random(0, 1),
number: max => _random(0, max),
'number, number': (min, max) => _random(min, max),
'Array | Matrix': size => _randomMatrix(size, 0, 1),
'Array | Matrix, number': (size, max) => _randomMatrix(size, 0, max),
'Array | Matrix, number, number': (size, min, max) => _randomMatrix(size, min, max)
});
function _randomMatrix(size, min, max) {
var res = randomMatrix(size.valueOf(), () => _random(min, max));
return isMatrix(size) ? size.create(res, 'number') : res;
}
function _random(min, max) {
return min + rng() * (max - min);
}
});
// number only implementation of random, no matrix support
// TODO: there is quite some duplicate code in both createRandom and createRandomNumber, can we improve that?
export var createRandomNumber = /* #__PURE__ */factory(name, ['typed', 'config', '?on'], _ref2 => {
var {
typed,
config,
on,
matrix
} = _ref2;
// seeded pseudo random number generator1
var rng = createRng(config.randomSeed);
if (on) {
on('config', function (curr, prev) {
if (curr.randomSeed !== prev.randomSeed) {
rng = createRng(curr.randomSeed);
}
});
}
return typed(name, {
'': () => _random(0, 1),
number: max => _random(0, max),
'number, number': (min, max) => _random(min, max)
});
function _random(min, max) {
return min + rng() * (max - min);
}
});

View File

@@ -0,0 +1,67 @@
import { factory } from '../../utils/factory.js';
import { randomMatrix } from './util/randomMatrix.js';
import { createRng } from './util/seededRNG.js';
import { isMatrix } from '../../utils/is.js';
var name = 'randomInt';
var dependencies = ['typed', 'config', '?on'];
export var createRandomInt = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
on
} = _ref;
// seeded pseudo random number generator
var rng = createRng(config.randomSeed);
if (on) {
on('config', function (curr, prev) {
if (curr.randomSeed !== prev.randomSeed) {
rng = createRng(curr.randomSeed);
}
});
}
/**
* Return a random integer number larger or equal to `min` and smaller than `max`
* using a uniform distribution.
*
* Syntax:
*
* math.randomInt() // generate a random integer between 0 and 1
* math.randomInt(max) // generate a random integer between 0 and max
* math.randomInt(min, max) // generate a random integer between min and max
* math.randomInt(size) // generate a matrix with random integer between 0 and 1
* math.randomInt(size, max) // generate a matrix with random integer between 0 and max
* math.randomInt(size, min, max) // generate a matrix with random integer between min and max
*
* Examples:
*
* math.randomInt(100) // returns a random integer between 0 and 100
* math.randomInt(30, 40) // returns a random integer between 30 and 40
* math.randomInt([2, 3]) // returns a 2x3 matrix with random integers between 0 and 1
*
* See also:
*
* random, pickRandom
*
* @param {Array | Matrix} [size] If provided, an array or matrix with given
* size and filled with random values is returned
* @param {number} [min] Minimum boundary for the random value, included
* @param {number} [max] Maximum boundary for the random value, excluded
* @return {number | Array | Matrix} A random integer value
*/
return typed(name, {
'': () => _randomInt(0, 1),
number: max => _randomInt(0, max),
'number, number': (min, max) => _randomInt(min, max),
'Array | Matrix': size => _randomIntMatrix(size, 0, 1),
'Array | Matrix, number': (size, max) => _randomIntMatrix(size, 0, max),
'Array | Matrix, number, number': (size, min, max) => _randomIntMatrix(size, min, max)
});
function _randomIntMatrix(size, min, max) {
var res = randomMatrix(size.valueOf(), () => _randomInt(min, max));
return isMatrix(size) ? size.create(res, 'number') : res;
}
function _randomInt(min, max) {
return Math.floor(min + rng() * (max - min));
}
});

View File

@@ -0,0 +1,20 @@
/**
* This is a util function for generating a random matrix recursively.
* @param {number[]} size
* @param {function} random
* @returns {Array}
*/
export function randomMatrix(size, random) {
var data = [];
size = size.slice(0);
if (size.length > 1) {
for (var i = 0, length = size.shift(); i < length; i++) {
data.push(randomMatrix(size, random));
}
} else {
for (var _i = 0, _length = size.shift(); _i < _length; _i++) {
data.push(random());
}
}
return data;
}

View File

@@ -0,0 +1,19 @@
import seedrandom from 'seedrandom';
var singletonRandom = /* #__PURE__ */seedrandom(Date.now());
export function createRng(randomSeed) {
var random;
// create a new random generator with given seed
function setSeed(seed) {
random = seed === null ? singletonRandom : seedrandom(String(seed));
}
// initialize a seeded pseudo random number generator with config's random seed
setSeed(randomSeed);
// wrapper function so the rng can be updated via generator
function rng() {
return random();
}
return rng;
}