Merge pull request #835 from HarrySarson/pow-fix

Extension of pow function to support Infinite exponents.
This commit is contained in:
Jos de Jong 2017-04-24 08:23:40 +02:00 committed by GitHub
commit a62b1c7fd6
2 changed files with 42 additions and 0 deletions

View File

@ -120,6 +120,23 @@ function factory (type, config, load, typed) {
// Unable to express y as a fraction, so continue on
}
// x^Infinity === 0 if -1 < x < 1
// A real number 0 is returned instead of complex(0)
if ((x*x < 1 && y === Infinity) ||
(x*x > 1 && y === -Infinity)) {
return 0;
}
// **for predictable mode** x^Infinity === NaN if x < -1
// N.B. this behavour is different from `Math.pow` which gives
// (-2)^Infinity === Infinity
if (config.predictable &&
((x < -1 && y === Infinity) ||
(x > -1 && x < 0 && y === -Infinity))) {
return NaN;
}
if (isInteger(y) || x >= 0 || config.predictable) {
return Math.pow(x, y);
}

View File

@ -131,6 +131,31 @@ describe('pow', function() {
assert.throws(function () {pow(1, 2, 3)}, /TypeError: Too many arguments in function pow \(expected: 2, actual: 3\)/);
});
it('should handle infitie exponents', function() {
var Ptbl = mathPredictable;
// TODO replace isNaN with complexInfinity when complex.js updates
assert.equal(math.pow( 3, Infinity), Infinity);
assert.equal(math.pow( 3, -Infinity), 0);
assert(isNaN(Ptbl.pow(-3, Infinity)));
assert( math.pow(-3, Infinity).isNaN());
assert.equal(math.pow(-3, -Infinity), 0);
assert.equal(math.pow( 0.3, Infinity), 0);
assert.equal(math.pow( 0.3, -Infinity), Infinity);
assert.equal(math.pow(-0.3, Infinity), 0);
assert(isNaN(Ptbl.pow(-0.3, -Infinity)));
assert( math.pow(-0.3, -Infinity).isNaN());
assert.equal(math.pow( Infinity, Infinity), Infinity);
assert.equal(math.pow( Infinity, -Infinity), 0); // https://www.wolframalpha.com/input/?i=infinity%5E(-infinity)
assert(isNaN(Ptbl.pow(-Infinity, Infinity)));
assert( math.pow(-Infinity, Infinity).isNaN());
assert.equal(math.pow(-Infinity, -Infinity), 0);
});
it('should exponentiate a complex number to the given power', function() {
approx.deepEqual(pow(complex(3, 0), 2), complex(9, 0));
approx.deepEqual(pow(complex(0, 2), 2), complex(-4, 0));