需要帮助将PV公式转换为PHP

时间:2014-02-27 15:36:34

标签: php excel-formula

我需要帮助将以下excel公式转换为PHP

PV(.0588/12,300,868.0583333)

我期待的输出是136,275.88,但我得到的输出是590573.166。我花了好几个小时,但似乎无法找到解决方案。

这是我的代码

function FV($rate = 0, $nper = 0, $pmt = 0, $pv =0, $type = 0)
{

    // Validate parameters
    if ($type != 0 && $type != 1) {
        return False;
    }

    // Calculate
    if ($rate != 0.0) {
        return -$pv * pow(1 + $rate, $nper) - $pmt * (1 + $rate * $type) * (pow(1 + $rate, $nper) - 1) / $rate;
    } else {
        return -$pv - $pmt * $nper;
    }
} //  function FV()
echo FV(.0588/12, 300, -868.06);

我之前已经阅读了similar帖子,但这并没有解决。

我也经历了PHP site,但这也无济于事。

1 个答案:

答案 0 :(得分:2)

您的算法适用于FV,但显然您需要PV。亚历杭德罗·佩德拉扎已经为此做了PEAR package Math_Finance,你很幸运。以下是提取的功能,以证明其有效( 您应该在项目中包含完整的Finance.php及其版权信息! )。

<?php
    /**
    * Extracted from the PEAR package Math_Finance by Alejandro Pedraza
    * http://pear.php.net/package/Math_Finance
    *
    * Returns the Present Value of a cash flow with constant payments and interest rate (annuities)
    * Excel equivalent: PV
    *
    *   TVM functions solve for a term in the following formula:
    *   pv(1+r)^n + pmt(1+r.type)((1+r)^n - 1)/r) +fv = 0
    *
    *
    * @param float      Interest rate per period 
    * @param int        Number of periods
    * @param float      Periodic payment (annuity)
    * @param float      Future Value
    * @param int        Payment type:
                            FINANCE_PAY_END (default):    at the end of each period
                            FINANCE_PAY_BEGIN:            at the beginning of each period
    * @return float     
    * @static
    * @access public
    */
    function presentValue($rate, $nper, $pmt, $fv = 0, $type = 0)
    {
        if ($nper < 0) {
            return PEAR::raiseError('Number of periods must be positive');
        }
        if ($type != FINANCE_PAY_END && $type != FINANCE_PAY_BEGIN) {
            return PEAR::raiseError('Payment type must be FINANCE_PAY_END or FINANCE_PAY_BEGIN');
        }

        if ($rate) {
            $pv = (-$pmt * (1 + $rate * $type) * ((pow(1 + $rate, $nper) - 1) / $rate) - $fv) / pow(1 + $rate, $nper);
        } else {
            $pv = -$fv - $pmt * $nper;
        }
        return $pv;
    }
?>

<强>用法

<?php   
    var_dump( presentValue(.0588/12,300,868.0583333) );
    // float(-136275.88429118)
?>

DEMO

注意

如前所述,您应该使用PEAR页面中的完整Finance.php文件,以使其完美地工作(因为您可能会收到未定义常量的通知,并且它不会引发错误)。您可以找到包HERE