From 2ef53ce0691e14b4f836032a4fc133ecddde700f Mon Sep 17 00:00:00 2001 From: Pavel Panchekha Date: Mon, 11 Aug 2014 17:30:23 -0700 Subject: [PATCH] Changed calculation of math.sqrt to avoid numerical problems when re < 0 --- lib/function/arithmetic/sqrt.js | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/lib/function/arithmetic/sqrt.js b/lib/function/arithmetic/sqrt.js index 0e65fd92b..0035eb987 100644 --- a/lib/function/arithmetic/sqrt.js +++ b/lib/function/arithmetic/sqrt.js @@ -52,17 +52,28 @@ module.exports = function (math) { if (isComplex(x)) { var r = Math.sqrt(x.re * x.re + x.im * x.im); - if (x.im >= 0) { - return new Complex( - 0.5 * Math.sqrt(2.0 * (r + x.re)), - 0.5 * Math.sqrt(2.0 * (r - x.re)) - ); + + var re, im; + + if (x.re >= 0) { + re = 0.5 * Math.sqrt(2.0 * (r + x.re)); } else { - return new Complex( - 0.5 * Math.sqrt(2.0 * (r + x.re)), - -0.5 * Math.sqrt(2.0 * (r - x.re)) - ); + re = Math.abs(x.im) / Math.sqrt(2 * (r - x.re)); + } + + if (x.re <= 0) { + im = 0.5 * Math.sqrt(2.0 * (r - x.re)); + } + else { + im = Math.abs(x.im) / Math.sqrt(2 * (r + x.re)); + } + + if (x.im >= 0) { + return new Complex(re, im); + } + else { + return new Complex(re, -im); } }