mathjs/lib/function/arithmetic/divideScalar.js
2015-08-03 23:36:00 -06:00

77 lines
1.8 KiB
JavaScript

'use strict';
function factory(type, config, load, typed) {
/**
* Divide two scalar values, `x / y`.
* This function is meant for internal use: it is used by the public functions
* `divide` and `inv`.
*
* This function does not support collections (Array or Matrix), and does
* not validate the number of of inputs.
*
* @param {number | BigNumber | Fraction | Complex | Unit} x Numerator
* @param {number | BigNumber | Fraction | Complex} y Denominator
* @return {number | BigNumber | Fraction | Complex | Unit} Quotient, `x / y`
* @private
*/
var divideScalar = typed('divide', {
'number, number': function (x, y) {
return x / y;
},
'Complex, Complex': _divideComplex,
'BigNumber, BigNumber': function (x, y) {
return x.div(y);
},
'Fraction, Fraction': function (x, y) {
return x.div(y);
},
'Unit, number': function (x, y) {
var res = x.clone();
res.value = ((res.value === null) ? res._normalize(1) : res.value) / y;
return res;
},
'number, Unit': function (x, y) {
var xUnit = new type.Unit(x);
return xUnit.divide(y);
},
'Unit, Unit': function (x, y) {
return x.divide(y);
}
});
/**
* Divide two complex numbers. x / y or divide(x, y)
* @param {Complex} x
* @param {Complex} y
* @return {Complex} res
* @private
*/
function _divideComplex (x, y) {
var den = y.re * y.re + y.im * y.im;
if (den != 0) {
return new type.Complex(
(x.re * y.re + x.im * y.im) / den,
(x.im * y.re - x.re * y.im) / den
);
}
else {
// both y.re and y.im are zero
return new type.Complex(
(x.re != 0) ? (x.re / 0) : 0,
(x.im != 0) ? (x.im / 0) : 0
);
}
}
return divideScalar;
}
exports.factory = factory;