Last active
August 29, 2015 14:04
-
-
Save aleksmitov/0d3200fbc166c756e325 to your computer and use it in GitHub Desktop.
Example of using the Bisection method, page 86 of "Competitive programming 3" by Steven & Felix Halim
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <iomanip> | |
| #include <algorithm> | |
| using namespace std; | |
| const double EPS = 1e-10; | |
| double f(double d, int m, int v, double i) | |
| { | |
| double loanLeft = v; | |
| for(int j = 0; j < m; ++j) | |
| { | |
| loanLeft = loanLeft*(1 + i/100); | |
| loanLeft -= d; | |
| } | |
| return loanLeft; | |
| } | |
| double bisection(int m, int v, double i) | |
| { | |
| double start = 0.01; | |
| double end = 1100; | |
| double mid; | |
| while(fabs(start - end) > EPS) | |
| { | |
| mid = (start + end) / 2; | |
| cout<<"Current mid: "<<mid<<", and current f: "<<f(mid, m, v, i)<<endl; | |
| if(f(mid, m, v,i) < 0) end = mid; | |
| else start = mid; | |
| } | |
| cout<<fixed<<setprecision(2)<<"D is: "<<mid<<endl; | |
| } | |
| int main() | |
| { | |
| int m = 2, v = 1000, i = 10; | |
| bisection(m, v, i); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment