Skip to content

Instantly share code, notes, and snippets.

@NanxingLAI
Created January 20, 2019 09:29
Show Gist options
  • Save NanxingLAI/fa20dd33997c20dfab78de30e6ce202a to your computer and use it in GitHub Desktop.
Save NanxingLAI/fa20dd33997c20dfab78de30e6ce202a to your computer and use it in GitHub Desktop.
task_4_exam
// main.cpp
// exam_4
//
// Created by Nanxing LAI on 2019/1/19.
// Copyright © 2019 Mac. All rights reserved.
//
#include<iostream>
#include<cmath>
#include<string>
#include<iomanip>
using namespace std;
//the check of interger number, only for the number of periods
int inputInteger(string prompt){
cout << prompt;
int n;
cin >> n;
while(n < 1){
cout << "invalid, " << prompt;
cin >> n;
}
return n;
}
// the test of double value number, which inluding r, pmt and pv
double inputDouble(string prompt){
cout << prompt;
double value;
cin >> value;
while(value < 0){
cout << "invalid, " << prompt;
cin >> value;
}
return value;
}
// we use secant method in this task, so we need define the f function firstly, which value shoulb be zero.
double f(double r,double pmt, double pv, int n)
{
return(pmt/pv-r*(1+1/(pow(1+r,n)-1)));
}
// we define the approximate pv satisfying the compounent interest formula: pmt*n=(1+r)^n*pv/n
// here we get the approximate function to calculate the PV
double approximateR(double pv, double pmt,int n)
{
double k,g;
k=n*pmt/pv;
g=1.00/n;
return(pow(k,g)-1);
}
int main()
{
double r,rnext,pv,pmt,temp,a,b;
int n;
// providing values
n = inputInteger("please input number of periods: ");
pv = inputDouble("please input present value: ");
pmt=inputDouble("please input the instalment: ");
r=approximateR(pv, pmt, n);// run the approximatePMT function above
rnext=r*0.95; //here we define the starting points
a=f(r,pmt,pv,n);
b=abs(a);
while(b>0.0001) //loop ends once the error smaller than 0.01;
{
temp=rnext-f(rnext,pmt,pv,n)*(rnext-r)/(f(rnext,pmt,pv,n)-f(r,pmt,pv,n));
r=rnext;
rnext=temp;
a=f(r,pmt,pv,n);
b=abs(a);
}
cout<<"the r is "<<r<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment