2014-05-18 22:21:00 +02:00

98 lines
2.5 KiB
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 matrix or a list with 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. Parameter `dim` is zero-based.
*
* Syntax:
*
* mean.mean(a, b, c, ...)
* mean.mean(A)
* mean.mean(A, dim)
*
* Examples:
*
* var math = mathjs();
*
* math.mean(2, 1, 4, 3); // returns 2.5
* math.mean([1, 2.7, 3.2, 4]); // returns 2.725
*
* math.mean([[2, 5], [6, 3], [1, 7]], 0); // returns [3, 5]
* math.mean([[2, 5], [6, 3], [1, 7]], 1); // returns [3.5, 4.5, 4]
*
* See also:
*
* median, min, max, sum, prod, std, var
*
* @param {... *} args A single matrix or or multiple scalar values
* @return {*} The mean of all values
*/
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);
}
};