title: Cubic Equations in Javascript
body: <p>I am trying to create a "cubic equations resolver app" in Javascript and I have a piece of code doing that in Matlab. It requires using complex numbers and i know that Javascript can't handle such numbers by itself so I use the MathJS library. I am trying to "traslate" the R code into Javascript code, but I don't get the right answers. Could anybody help me to traslate it appropriately?</p>
  
  <pre><code>    I try to calculate cubic roots of: "x^3 + -4x^2 - 7x - 10 = 0". 
  
      Output in Matlab: "X1 = 5,5768 X2 = -0.07884 + 1.0824i X3 = -0.7884  - 1.0824i".
  
      Output in Javascript: "X1 = 5.5768 X2 = 1.333 - 2.5925i X3 = 1.333 - 2.5925i".
  </code></pre>
  
  <p>Where is my mistake?
  Thanks you.</p>
  
  <p>MATLAB:</p>
  
  <pre><code>clear
  clc
  %Equations Coefficients
  p=-4; q=-7 r=-10;
  k = (3 * q - p^2) / 3;
  m = (2 * p^3 - 9 * p * q + 27 * r) /2;
  c = m^2/4 + k^3 / 27;
  A = (-m/2 + sqrt(c))^1/3;
  B = (-m/2 - sqrt(c))^1/3;]
  z1 = A + B;
  z2 = 0.5 * (-(A+B)+(A-B)*sqrt(-3));
  z3 = 0.5 * (-(A+B)-(A-B)*sqrt(-3));
  %Equation Roots
  x1 = z1 -p/3;
  x2 = z2 -p/3;
  x3 = z3 -p/3;
  </code></pre>
  
  <p>JAVASCRIPT:</p>
  
  <pre><code>var mensaje = "";
  var mmath = mathjs();
  var fields= document.getElementsByClassName('elements');
  
  if (fields.length == 4){
      for (var i = 0; i&lt;fields.length;i++){
          coef[i] = Number(fields[i].value);  
      }
  }
  
  if (coef[0] != 0) {
      var p = coef[1] / coef[0];
      var q = coef[2] / coef[0];
      var r = coef[3] / coef[0];
      var k = ((3 * q) - Math.pow(p,2))/3;
      var m = ((2 * Math.pow(p,3)) - (9 * p * q) + (27 * r )) / 27;
      var c1 = (Math.pow(m,2))/4;
      var c2 = (Math.pow(k,3))/27;
      var c = c1 + c2;
      var A1 = mmath.pow((-(m*0.5) + mmath.sqrt(c)),(1/3));
      var B1 = mmath.pow((-(m*0.5) - mmath.sqrt(c)),(1/3));
      var A = mmath.complex(A1);
      var B = mmath.complex(B1);
      var ApB = mmath.add(A,B);
      var AmB = mmath.add(A,-B);
      var sqrt3 = mmath.sqrt(-3);
      var z1 = ApB;
      var z2a = mmath.add(-ApB,AmB);
      var z2b = mmath.multiply(z2a,sqrt3);
      var z2 = mmath.multiply(z2b, 0.5);
      var z3a = mmath.add(-ApB,-AmB);
      var z3b = mmath.multiply(z3a,sqrt3);
      var z3 = mmath.multiply(z2b, 0.5);
      var f = -p/3;
      var x1 = mmath.add(z1,f);
      var x2 = mmath.add(z2,f);
      var x3 = mmath.add(z3,f);
      sol3[0] = "X1: " + x1 + "\n";
      sol3[1] = "X2: " + x2 + "\n";
      sol3[2] = "X3: " + x3 + "\n";
  
      for (var i = 0; i &lt; 3; i++){
          mensaje+=sol3[i];
      };
      alert(""+mensaje);
  };
  </code></pre>