troubleshooting Question

# Calculating apr using newton raphson (in php) - how to add upfront fee

PHPMath / Science
I am trying to calculate APR using Newton Raphson in PHP. I have modified the code from this question into php

http://stackoverflow.com/questions/3102476/calculating-annual-percentage-rate-need-some-help-with-inherited-code

However the formula in this question is based on an initial principal, recurring monthly payments and a total number of payments. I need my APR calculation to include an initial start up fee. This would be added to the first monthly payment meaning the monthly payments are no longer all the the same. I take it that this would alter the original formula and hence its derivative. I have no idea what to use now as the initial formula or how to modify this

Here is the php
``````\$numPay = 12;
\$payment = 875;
\$amount = 10000;
\$error = pow(10,-5);
\$approx = 0.05/12; // let's start with a guess that the APR is 5%
\$prev_approx;

function f(\$x) {
global \$numPay;
global \$payment;
global \$amount;
global \$error;

return \$amount * \$x * (pow(1 + \$x,\$numPay)/(pow(1 + \$x, \$numPay) - 1)) - \$payment;

}

function f_prime(\$x) {
global \$numPay;
global \$payment;
global \$amount;
global \$error;

return \$amount * (pow(1 + \$x,\$numPay)/(-1 + pow(1 + \$x,\$numPay)) - \$numPay * \$x * pow(1 + \$x,-1 + 2*\$numPay)/pow(-1 + pow(1 + \$x,\$numPay),2) + \$numPay * \$x * pow(1 + \$x,-1 + \$numPay)/(-1 + pow(1 + \$x,\$numPay)));

}
echo f(\$approx) . "<br/>";

echo f_prime(\$approx) . "<br/>";
echo  "initial guess \$approx" . "<br/>";

for (\$k=0;\$k<20; \$k++) {
\$prev_approx = \$approx;
\$approx = \$prev_approx - (f(\$prev_approx)/f_prime(\$prev_approx));
\$diff = abs(\$approx-\$prev_approx);
echo "new guess \$approx diff is \$diff <br/>";
if (\$diff < \$error) break;
}

\$apr = round(\$approx * 12 * 10000 /100, 1); // this way we get APRs like 7.5% or 6.55%
echo "apr is \$apr %";
``````
###### Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.