title: Durand-Kerner method to find roots of nonlinear equation
body: <p>I am being asked to find the roots of f(x) = 5x(e^-mod(x))cos(x) + 1 . I have previously used the Durand-Kerner method to find the roots of the function x^4 -3x^3 + x^2 + x + 1 with the code shown below. I thought I could simply reuse the code to find the roots of f(x) but whenever I replace x^4 -3x^3 + x^2 + x + 1 with f(x) the program outputs nan for all the roots. What is wrong with my Durand-Kerner implementation and how do I go about modifying it to work for f(x)? I would be very grateful for any help. </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;complex&gt;
  #include &lt;math.h&gt;
  
  using namespace std;
  
  typedef complex&lt;double&gt; dcmplx;
  
  dcmplx f(dcmplx x)
  {
      // the function we are interested in
      double a4 = 1;
      double a3 = -3;
      double a2 = 1;
      double a1 = 1;
      double a0 = 1;
  
      return (a4 * pow(x,4) + a3 * pow(x,3) + a2 * pow(x,2) + a1 * x + a0);
  }
  
  
  int main()
  {
  
  dcmplx p(.9,2);
  dcmplx q(.1, .5);
  dcmplx r(.7,1);
  dcmplx s(.3, .5);
  
  dcmplx p0, q0, r0, s0;
  
  int max_iterations = 100;
  bool done = false;
  int i=0;
  
  while (i&lt;max_iterations &amp;&amp; done == false)
  {
      p0 = p;
      q0 = q;
      r0 = r;
      s0 = s;
  
  
  p = p0 - f(p0)/((p0-q)*(p0-r)*(p0-s));
  q = q0 - f(q0)/((q0-p)*(q0-r)*(q0-s));
  r = r0 - f(r0)/((r0-p)*(r0-q)*(r0-s0));
  s = s0 - f(s0)/((s0-p)*(s0-q)*(s0-r));
  
      // if convergence within small epsilon, declare done
      if (abs(p-p0)&lt;1e-5 &amp;&amp; abs(q-q0)&lt;1e-5 &amp;&amp; abs(r-r0)&lt;1e-5 &amp;&amp; abs(s-s0)&lt;1e-5)
          done = true;
  
      i++;
  }
  
  cout&lt;&lt;"roots are :\n";
  cout &lt;&lt; p &lt;&lt; "\n";
  cout &lt;&lt; q &lt;&lt; "\n";
  cout &lt;&lt; r &lt;&lt; "\n";
  cout &lt;&lt; s &lt;&lt; "\n";
  cout &lt;&lt; "number steps taken: "&lt;&lt; i &lt;&lt; endl;
  
  return 0;
  }
  </code></pre>
  
  <p>The only thing I have been changing so far is the dcmplx f function. I have been changing it to </p>
  
  <pre><code>dcmplx f(dcmplx x)
  {
      // the function we are interested in
      double a4 = 5;
  
      double a0 = 1;
  
      return (a4 * x * exp(-x) * cos(x) )+ a0;
  }
  </code></pre>