Repository: josdejong/mathjs (js)

Issue:
abs(0 + 0i) evaluates to NaN
Attempting to evaluate abs(0 + 0i) returns NaN. This appears to be an unnoticed edge case in avoiding overflows when calculating the absolute value of a complex number.

abs(0 + 0i) should, obviously, return 0.

Pull request:
Fix #328 abs(0+0*i) evaluates to NaN
This is a quick fix. This might need a better solution though (
numerical instabilities still remain ).

Patch:
diff --git a/lib/function/arithmetic/abs.js b/lib/function/arithmetic/abs.js
index 83e2e1fc2..f81558d29 100644
--- a/lib/function/arithmetic/abs.js
+++ b/lib/function/arithmetic/abs.js
@@ -49,6 +49,12 @@ module.exports = function (math) {
       // do not compute sqrt(re * re + im * im) since it will overflow with big numbers!
       var re = Math.abs(x.re);
       var im = Math.abs(x.im);
+      if (re == 0) {
+        return im;
+      }
+      if (im == 0) {
+        return re;
+      }
       if (re >= im) {
         var i = im / re;
         return re * Math.sqrt(1 + i * i);


Test patch:
diff --git a/test/function/arithmetic/abs.test.js b/test/function/arithmetic/abs.test.js
index 6a2ed8060..d1f5468de 100644
--- a/test/function/arithmetic/abs.test.js
+++ b/test/function/arithmetic/abs.test.js
@@ -32,6 +32,12 @@ describe('abs', function () {
     assert.equal(math.norm(math.complex(-4e200, 1e200)), 4.12310562561766e+200);
   });
 
+  it('should return the absolute number of a complex number with zero', function () {
+    assert.equal(math.abs(math.complex(1, 0)), 1);
+    assert.equal(math.abs(math.complex(0, 1)), 1);
+    assert.equal(math.abs(math.complex(0, 0)), 0);
+  });
+
   it('should return the absolute value of all elements in a matrix', function () {
     var a1 = math.abs(math.matrix([1,-2,3]));
     assert.ok(a1 instanceof math.type.Matrix);