From a5692e1d0a176dc2320b2b030accad86091e286e Mon Sep 17 00:00:00 2001 From: Harry Sarson Date: Sun, 23 Apr 2017 13:13:23 +0100 Subject: [PATCH] Extension of pow function to support Infinite exponents. --- lib/function/arithmetic/pow.js | 17 +++++++++++++++++ test/function/arithmetic/pow.test.js | 25 +++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/lib/function/arithmetic/pow.js b/lib/function/arithmetic/pow.js index 9ed92827d..47553248c 100644 --- a/lib/function/arithmetic/pow.js +++ b/lib/function/arithmetic/pow.js @@ -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); } diff --git a/test/function/arithmetic/pow.test.js b/test/function/arithmetic/pow.test.js index 10897da97..267f1842c 100644 --- a/test/function/arithmetic/pow.test.js +++ b/test/function/arithmetic/pow.test.js @@ -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));