Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- using namespace std;
- // This function if is 0 is the solutioon of sqrt(2) - n = 0
- double f(double n){
- return sqrt(2) - n;
- }
- // function that returns the "sign" of the value -1, 0 for 0 or, 1 for positive
- template <typename T> int sgn(T val) {
- return (T(0) < val) - (val < T(0));
- }
- int main()
- {
- //------------------ user inputs --------------------------------------
- // define the search interval
- double lower = 0, upper = 2.0;
- // define the tolerance
- double tolerance = 0.001;
- // define the max iterations
- int n_max = 15;
- //------------------ algorithm starts --------------------------------------
- // if the algorithm is precise enough this will be true
- bool result_found = false;
- // start by searching in the middle of the interval
- double half = (upper + lower) / 2.0;
- int n_itr = 0;
- while(n_itr < n_max){
- // calculate the half point
- double res = f(half);
- // if the half point is 0 or the half point is lower than the tolerance
- // end the porgram
- if(res == 0 || ((upper - lower) / 2) < tolerance ){
- cout << "result: " << half << endl;
- cout << "in n iterations: " << n_itr << endl;
- result_found = true;
- break;
- }
- // check which sign is the f(c) and f(lower), if they have the same sign
- // ex. f(c) > 0 and f(lower) > 0, then set the lower limit to the half
- // else the uppper limit is set to half
- // (alternative sign check res * f(lower) > 0)
- if( sgn<double>(res) == sgn<double>(f(lower)) ){
- lower = half;
- half = (lower + upper) / 2;
- }
- else{
- upper = half;
- half = (lower + upper) / 2;
- }
- // shows the interval getting smaller
- cout << "lower: " << lower << " half: " << half << " upper: " << upper << endl;
- n_itr += 1;
- }
- if(!result_found){
- cout << "Not enough iteration to reach the tolerance" << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment