tags:

views:

99

answers:

3

Hi,

the code is below, I am trying to call the "RATE" function.

RATE(120, -271.09, 20000) is how it is used in excel, with this code I think it should work the same.

What am I doing wrong? how can I get it to work

My code is here: http://pastebin.com/AbKqc8g1

+2  A: 

The code posted at your URL is defining a class structure for whatever your application is. Therefore you would need to create an instance of the class before you call any functions within that class. For example, the following should help get you started:

$financial = new Financial;

$rate = $financial->RATE(120,-271.09,20000);

print_r($rate);

Quite how you are trying to use this within your application is unclear but using the above principle you should start to see some output.

simnom
+1  A: 

You have to make an instance of this class and then run the RATE method.

<?php
    require("class.Financial.php"); 
    $fin     = new Financial(); 
    $result  = $fin->RATE(120, -271.09, 20000);
    echo $result;
?>
Alex
Thanks, that almost worked.I think there must be something wrong with the function, because it outputs values 2 decimal places out, which results in a "NAN" for any numbers over 250 or so.e.g. putting -27 in there should output -2.420974 but instead it outputs -0.02420974
James
A: 

@ Scott M

here is the function:

/**
 * RATE
 * 
 **/
function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1)
{
    $rate = $guess;
    $i  = 0;
    $x0 = 0;
    $x1 = $rate;

    if (abs($rate) < FINANCIAL_ACCURACY) {
        $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
    while ((abs($y0 - $y1) > FINANCIAL_ACCURACY) && ($i < FINANCIAL_MAX_ITERATIONS))
    {
        $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0);
        $x0 = $x1;
        $x1 = $rate;

        if (abs($rate) < FINANCIAL_ACCURACY) {
            $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;
}
James