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.
68 lines (57 loc) • 1.75 kB
JavaScript
module.exports = function (math) {
var util = require('../../util/index'),
BigNumber = math.type.BigNumber,
Complex = require('../../type/Complex'),
Unit = require('../../type/Unit'),
collection = require('../../type/collection'),
isNumber = util.number.isNumber,
isBoolean = util['boolean'].isBoolean,
isComplex = Complex.isComplex,
isUnit = Unit.isUnit,
isCollection = collection.isCollection;
/**
* Calculate the cosine of a value
*
* cos(x)
*
* For matrices, the function is evaluated element wise.
*
* @param {Number | Boolean | Complex | Unit | Array | Matrix} x
* @return {Number | Complex | Array | Matrix} res
*
* @see http://mathworld.wolfram.com/Cosine.html
*/
math.cos = function cos(x) {
if (arguments.length != 1) {
throw new math.error.ArgumentsError('cos', arguments.length, 1);
}
if (isNumber(x)) {
return Math.cos(x);
}
if (isComplex(x)) {
// cos(z) = (exp(iz) + exp(-iz)) / 2
return new Complex(
0.5 * Math.cos(x.re) * (Math.exp(-x.im) + Math.exp(x.im)),
0.5 * Math.sin(x.re) * (Math.exp(-x.im) - Math.exp(x.im))
);
}
if (isUnit(x)) {
if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
throw new TypeError ('Unit in function cos is no angle');
}
return Math.cos(x.value);
}
if (isCollection(x)) {
return collection.deepMap(x, cos);
}
if (isBoolean(x)) {
return Math.cos(x);
}
if (x instanceof BigNumber) {
// TODO: implement BigNumber support
// downgrade to Number
return cos(x.toNumber());
}
throw new math.error.UnsupportedTypeError('cos', math['typeof'](x));
};
};