mirror of
https://github.com/josdejong/mathjs.git
synced 2026-01-18 14:59:29 +00:00
Added reduce calls from "mean" function
This commit is contained in:
parent
b0ce2686c3
commit
f43523b301
@ -28,7 +28,7 @@ module.exports = function (math) {
|
||||
else if (arguments.length == 2) {
|
||||
// mean([a, b, c, d, ...], dim)
|
||||
// TODO: implement support for calculating the mean over specified dimension
|
||||
throw new Error('Specifying a dimension is not yet implemented...');
|
||||
return _nmean(arguments[0], arguments[1]-1);
|
||||
}
|
||||
else {
|
||||
throw new SyntaxError('Wrong number of parameters');
|
||||
@ -40,6 +40,25 @@ module.exports = function (math) {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Calculate the mean value in an n-dimensional array, returning a
|
||||
* n-1 dimensional array
|
||||
* @param {Array} array
|
||||
* @param {Number} dimension
|
||||
* @return {Number} mean
|
||||
* @private
|
||||
*/
|
||||
function _nmean(array, dim){
|
||||
var sum, len, tmp;
|
||||
sum = collection.reduce(array, dim, math.add);
|
||||
tmp = array;
|
||||
while(--dim){
|
||||
tmp = tmp[0];
|
||||
}
|
||||
len = tmp.length;
|
||||
return math.divide(sum/len);
|
||||
};
|
||||
|
||||
/**
|
||||
* Recursively calculate the mean value in an n-dimensional array
|
||||
* @param {Array} array
|
||||
|
||||
@ -36,6 +36,15 @@ describe('mean', function() {
|
||||
])), 5);
|
||||
});
|
||||
|
||||
it('should return the mean value along a dimension on a matrix', function() {
|
||||
assert.deepEqual(math.mean([
|
||||
[2, 6],
|
||||
[4, 10]],2), [4, 7]);
|
||||
assert.deepEqual(math.mean([
|
||||
[2, 6],
|
||||
[4, 10]],1), [3, 8]);
|
||||
});
|
||||
|
||||
it('should throw an error if called with invalid number of arguments', function() {
|
||||
assert.throws(function() {math.mean()});
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user