基于PHPExcel的函数RATE()返回不正确的值

时间:2015-02-11 10:53:16

标签: php phpexcel financial

最新版本,在此处找到:https://phpexcel.codeplex.com/SourceControl/latest#trunk/Classes/PHPExcel/Calculation/Financial.php的RATE()函数对我不起作用。

我创建了一个新的PHP页面,删除了该特定功能并对其进行了测试,但输出与Excel的差别很大。

<?php
define('FINANCIAL_MAX_ITERATIONS', 128); 
define('FINANCIAL_PRECISION', 1.0e-08); 

function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1) {
        //$nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
        //$pmt  = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
        //$pv       = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
        //$fv       = (is_null($fv))    ? 0.0   :   PHPExcel_Calculation_Functions::flattenSingleValue($fv);
        //$type = (is_null($type))  ? 0     :   (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
        //$guess    = (is_null($guess)) ? 0.1   :   PHPExcel_Calculation_Functions::flattenSingleValue($guess);

        $rate = $guess;
        if (abs($rate) < FINANCIAL_PRECISION) {
            $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
        } else {
            $f = exp($nper * log(1 + $rate));
            $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
        }
        $y0 = $pv + $pmt * $nper + $fv;
        $y1 = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;

        // find root by secant method
        $i  = $x0 = 0.0;
        $x1 = $rate;
        while ((abs($y0 - $y1) > FINANCIAL_PRECISION) && ($i < FINANCIAL_MAX_ITERATIONS)) {
            $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0);
            $x0 = $x1;
            $x1 = $rate;
            if (($nper * abs($pmt)) > ($pv - $fv))
                $x1 = abs($x1);

            if (abs($rate) < FINANCIAL_PRECISION) {
                $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
            } else {
                $f = exp($nper * log(1 + $rate));
                $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
            }

            $y0 = $y1;
            $y1 = $y;
            ++$i;
        }
        return $rate;
    }   //  function RATE()

$nper = 180;
$pmt = 6729.045954705334;
$pv = -400000;

$test = RATE($nper, $pmt, $pv);
?>

上面的函数调用产生:0.008774735218308

Excel 2013:

=RATE(180;6729,04595470533;-400000)

收益率:0,0158263127885

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我设置了一些静态值并检查了值是否在其中。在那种情况下,我使用一个$猜测,否则我使用不同的$猜测。在Excel中,无论$ guess和值都传递它都可以工作。