 # Rate() returning NAN

a guest
Apr 6th, 2012
178
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. //The following consts are defined:
2. //FINANCIAL_PRECISION=1.0e-08
3. //FINANCIAL_MAX_ITERATIONS=128
4.
5.
6. //Function by PHPExcel project;
7. protected function RATE(\$nper, \$pmt, \$pv, \$fv = 0.0, \$type = 0, \$guess = 0.1) {
8.         \$rate = \$guess;
9.         if (abs(\$rate) < self::FINANCIAL_PRECISION) {
10.             \$y = \$pv * (1 + \$nper * \$rate) + \$pmt * (1 + \$rate * \$type) * \$nper + \$fv;
11.         } else {
12.             \$f = exp(\$nper * log(1 + \$rate));
13.             \$y = \$pv * \$f + \$pmt * (1 / \$rate + \$type) * (\$f - 1) + \$fv;
14.         }
15.         \$y0 = \$pv + \$pmt * \$nper + \$fv;
16.         \$y1 = \$pv * \$f + \$pmt * (1 / \$rate + \$type) * (\$f - 1) + \$fv;
17.
18.         // find root by secant method
19.         \$i  = \$x0 = 0.0;
20.         \$x1 = \$rate;
21.         while ((abs(\$y0 - \$y1) > self::FINANCIAL_PRECISION) && (\$i < self::FINANCIAL_MAX_ITERATIONS)) {
22.             \$rate = (\$y1 * \$x0 - \$y0 * \$x1) / (\$y1 - \$y0);
23.             \$x0 = \$x1;
24.             \$x1 = \$rate;
25.
26.             if (abs(\$rate) < self::FINANCIAL_PRECISION) {
27.                 \$y = \$pv * (1 + \$nper * \$rate) + \$pmt * (1 + \$rate * \$type) * \$nper + \$fv;
28.             } else {
29.                 \$f = exp(\$nper * log(1 + \$rate));
30.                 \$y = \$pv * \$f + \$pmt * (1 / \$rate + \$type) * (\$f - 1) + \$fv;
31.             }
32.
33.             \$y0 = \$y1;
34.             \$y1 = \$y;
35.             ++\$i;
36.         }
37.         return \$rate;
38.     }
RAW Paste Data