mathjs/lib/function/arithmetic/divideScalar.js

64 lines
1.6 KiB
JavaScript

'use strict';
module.exports = function (config) {
var typed = require('typed-function');
var Complex = require('../../type/Complex');
/**
* 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 | Boolean | Complex | Unit | null} x Numerator
* @param {Number | BigNumber | Boolean | Complex | null} y Denominator
* @return {Number | BigNumber | Complex | Unit} Quotient, `x / y`
* @private
*/
var divideScalar = typed('divideScalar', {
'number, number': function (x, y) {
return x / y;
},
'Complex, Complex': _divideComplex,
'BigNumber, BigNumber': 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;
}
});
/**
* 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 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 Complex(
(x.re != 0) ? (x.re / 0) : 0,
(x.im != 0) ? (x.im / 0) : 0
);
}
}
return divideScalar;
};