title: How can I calculate an interest rate in PHP?
body: <p>So I searched everywhere but I couldn't find an appropriate solution to my problem. I need to calculate the (annual) interest rate in PHP.</p>
  
  <p>The function RATE on PHPExcel doesn't work (<a href="https://stackoverflow.com/questions/10050846/phpexcel-based-function-rate-returning-nan">returning NaN</a>), and I tried to use <a href="http://finance.thinkanddone.com/finding_irr_with_tvm_equation_using_newton_raphson_method.html" rel="nofollow noreferrer">this</a>
  to write an other function that gives me the interest rate of an investment when you have : the original amount, the final amount, the constant payment (the amount saved for a month) and the period (in months) of the investment.</p>
  
  <p>But it still doesn't work. Here is the code if it can helps. </p>
  
  <pre><code>public function calculateRate($originalAmount, $finalAmount, $monthlySavings, $savingsPeriod) {
      define('FINANCIAL_MAX_ITERATIONS', 128);
      define('FINANCIAL_PRECISION', 1.0e-06);
  
      $rate = 0.05; // guess 
      $i = 0;
  
      do {
          $equ = $monthlySavings * (pow(1 + $rate, $savingsPeriod) - 1) / $rate + $originalAmount * pow(1 + $rate, $savingsPeriod) + $finalAmount;
          $derivative = ( $monthlySavings * ( $savingsPeriod * $rate * pow(1 + $rate, $savingsPeriod - 1 ) - pow(1 + $rate, $savingsPeriod) ) + 1 ) / ($rate * $rate) + $savingsPeriod * $originalAmount * pow(1 + $rate, $savingsPeriod - 1);
          $div = $equ / $derivative;
          $oldRate = $rate;
          $rate -= $div;
          ++$i;
          var_dump($i, $rate, $equ, $derivative, $div);
      } while (abs($div) &gt; FINANCIAL_PRECISION &amp;&amp; ($i &lt; FINANCIAL_MAX_ITERATIONS));
  
      return $rate;
  }
  </code></pre>
  
  <p>I need a function that can calculate the interest rate but I can't find anything that works...</p>