Last active
October 4, 2016 11:03
-
-
Save antonioalmeida/9a72fb10b8ba204199466f4293fbeec6 to your computer and use it in GitHub Desktop.
Quick bissection implementation
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
//============================================================================ | |
// Name : bissection.cpp | |
// Author : theantonioalmeida | |
// Description : Quick bissection implementation | |
//============================================================================ | |
#include <iostream> | |
#include <iomanip> | |
#include <cstdlib> | |
#include <cmath> | |
#include <limits> | |
using namespace std; | |
double f(double x); | |
int main() { | |
double a, b, precision, lastPeriod; | |
int counter = 0; | |
cout << "a b precision "<< endl; | |
cin >> a >> b >> precision; | |
double m; | |
while(abs(b-a) > precision) { | |
m = (a+b)/2.0; | |
if(signbit(f(a)) != signbit(f(m))) | |
b = m; | |
else | |
a = m; | |
//increment counter | |
counter++; | |
//infinite loop test | |
if (lastPeriod == abs(b-a)) { | |
cout << "The process entered an infinite loop." << endl; | |
return -1; | |
} | |
else | |
lastPeriod = abs(b-a); | |
} | |
cout << "The function's zero is " << setprecision(3) << fixed << (a+b)/2.0 << " with a precision of "; | |
cout << (a-b)/2.0 << ", found after " << counter << " iterations." << endl; | |
return 0; | |
} | |
double f(double x) { | |
return pow(x,2)-2; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment