-
March 23rd, 2014, 04:33 AM
#1
Excel RATE() function in Java behaving slightly differently
Hi guys,
Just wanted to check something. I have the following function below which is the equivalent of the RATE function in Excel
In Excel, if I do the following in any cell: =RATE(68, -118161.59, 4146470.27) - it gives me: 2.2014989%
However, the below code gives me: 0.0220150136..
I am expecting it to give me 0.0022014989
It is only marginally out, but can anyone point me why it is marginally out?
Any help would be much appreciated
Code:
public static void main(String[] args)
{
double rate1 = Financials.rate(68, 118161.59, 4146470.27);
System.out.println(rate1);
System.out.println("finished");
}
Code:
public static double rate(double nper, double pmt, double pv)
{
double error = 0.0000001;
double high = 1.00;
double low = 0.00;
double rate = (2.0 * (nper * pmt - pv)) / (pv * nper);
while(true) {
// check for error margin
double calc = Math.pow(1 + rate, nper);
calc = (rate * calc) / (calc - 1.0);
calc -= pmt / pv;
if (calc > error) {
// guess too high, lower the guess
high = rate;
rate = (high + low) / 2;
} else if (calc < -error) {
// guess too low, higher the guess
low = rate;
rate = (high + low) / 2;
} else {
// acceptable guess
break;
}
}
//System.out.println("Rate : "+rate);
return rate;
}
Last edited by capricorn86; March 23rd, 2014 at 04:47 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|