mathjs
Version:
Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser and offers an integrated solution to work with numbers, big numbers, complex numbers, units, and matrices.
82 lines (72 loc) • 2.06 kB
JavaScript
module.exports = function (math) {
var Matrix = require('../../type/Matrix'),
collection = require('../../type/collection'),
isCollection = collection.isCollection,
size = require('../../util/array').size;
/**
* Compute the mean value of a list of values
* In case of a multi dimensional array, the mean of the flattened array
* will be calculated. When dim is provided, the maximum over the selected
* dimension will be calculated.
*
* mean(a, b, c, ...)
* mean(A)
* mean(A, dim)
*
* @param {... *} args A single matrix or or multiple scalar values
* @return {*} res
*/
math.mean = function mean(args) {
if (arguments.length == 0) {
throw new SyntaxError('Function mean requires one or more parameters (0 provided)');
}
if (isCollection(args)) {
if (arguments.length == 1) {
// mean([a, b, c, d, ...])
return _mean(args);
}
else if (arguments.length == 2) {
// mean([a, b, c, d, ...], dim)
return _nmean(arguments[0], arguments[1]);
}
else {
throw new SyntaxError('Wrong number of parameters');
}
}
else {
// mean(a, b, c, d, ...)
return _mean(arguments);
}
};
/**
* Calculate the mean value in an n-dimensional array, returning a
* n-1 dimensional array
* @param {Array} array
* @param {Number} dim
* @return {Number} mean
* @private
*/
function _nmean(array, dim){
var sum;
sum = collection.reduce(array, dim, math.add);
return math.divide(sum, size(array)[dim]);
}
/**
* Recursively calculate the mean value in an n-dimensional array
* @param {Array} array
* @return {Number} mean
* @private
*/
function _mean(array) {
var sum = 0;
var num = 0;
collection.deepForEach(array, function (value) {
sum = math.add(sum, value);
num++;
});
if (num === 0) {
throw new Error('Cannot calculate mean of an empty array');
}
return math.divide(sum, num);
}
};