Advertisement
Guest User

PHP APR Calculation

a guest
Jul 11th, 2011
469
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.49 KB | None | 0 0
  1. <?php
  2. // equation derived from explanation on wikipedia.
  3. // by @sweetl80
  4.  
  5. // 10.2
  6. $term = 35; // duration minus one.
  7. $monthly_payment = 474.19;
  8. $total_credit = 21820.50;
  9. $final_payment = 9873;
  10.  
  11. $t_apr = 0;
  12. $npv = 0;
  13.  
  14. // ultimately, these are used for attempting to speed up the calculation with a staged increment system.
  15. $limit[1] = $total_credit * 0.00078;
  16. $limit[2] = $total_credit * 0.00030;
  17. $limit[3] = $total_credit * 0.00010;
  18.  
  19. while (!$found){   
  20.     $npv_perc = round(($npv / $total_credit) * 100,4);
  21.    
  22.     /*
  23.      * attempting staged increment
  24.      */
  25.     if ($npv_perc >= $limit[1]) $t_apr += 0.01;  // lop off two decimal places (fast increment of apr)
  26.     if ($npv_perc < $limit[1] && $npv_perc >= $limit[2]) $t_apr += 0.001; // add a hundredth. (slower increment)
  27.     if ($npv_perc < $limit[2] && $npv_perc >= $limit[3]) $t_apr += 0.0001; // slower still.
  28.     if ($npv_perc < $limit[3]) $t_apr += 0.00001; // the slowest, for accuracy.
  29.    
  30.     /*
  31.      * if you dont like the 'staged' setup above, you could just do this instead, but it can lead to hundreds of thousands of calculations
  32.     // $t_apr += 0.00001; // slow, but accurate.
  33.      */
  34.    
  35.     $npv = -$total_credit;
  36.        
  37.     for ($m = 1; $m <= $term; $m++){
  38.         if ($m < $term){
  39.             $val = $monthly_payment;
  40.         } else {
  41.             $val = $monthly_payment + $final_payment;
  42.         }
  43.        
  44.         $npv += ($val / pow(1 + $t_apr,$m/12));
  45.     }
  46.    
  47.     $loops++;
  48.    
  49.     if ($npv <= 0){
  50.         $apr = round($t_apr * 100,1);
  51.         break;
  52.     }
  53. }
  54.  
  55. ?>
  56.  
  57. <h1><?=$apr?> found after <?=$loops?> loops</h1>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement