Skip to content

Instantly share code, notes, and snippets.

@stephlocke
Created September 17, 2014 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephlocke/462e9c3b2ebd19b64ed1 to your computer and use it in GitHub Desktop.
Save stephlocke/462e9c3b2ebd19b64ed1 to your computer and use it in GitHub Desktop.
internally used rate function from optiRum::RATE written in C++
library(Rcpp)
cppFunction('double rate(double nper, double pmt, double pv){
float rate1 = 0.01 ;
float rate2 = 0.05 ;
float newrate = 0 ;
int n = 10;
for (int i = 0; i < n; ++i) {
double pv1 = floor((-pmt/rate1 * (1 - 1/pow((1 + rate1),nper)))*100+0.5)/100 - pv ;
double pv2 = floor((-pmt/rate2 * (1 - 1/pow((1 + rate2),nper)))*100+0.5)/100 - pv ;
if (pv1 != pv2) {
newrate = (pv1 * rate2 - pv2 * rate1)/(pv1 - pv2) ;
}
if (abs(pv1) > abs(pv2)) {
rate1 = newrate ;
}
else {
rate2 = newrate ;
}
}
return rate1;
}')
rate(12,-500,3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment