Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <iomanip>
- #include <stdexcept>
- using namespace std;
- // This function if is 0 is the solutioon of sqrt(2) - n = 0
- double f(double n){
- return n*n - 2;
- //return n*n*n*n - n*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));
- }
- // contains the result of the function bysect, the iteration count and the
- // resulting number to calculate the error
- struct BisectResult{
- int itr_count;
- double result;
- };
- // type of function pointer f(x)
- typedef double (*fptr_t) (double);
- // calculates how many iterations to reach the given tolerance
- BisectResult bisect(double lower, double upper, double tolerance, fptr_t func){
- int itr_max = 10000;
- int itr_count = 0;
- BisectResult bs_res;
- double half = (upper + lower) / 2.0;
- double res;
- do{
- res = func(half);
- bs_res.result = half;
- bs_res.itr_count = itr_count;
- if( sgn<double>(res) == sgn<double>(f(lower)) ){
- lower = half;
- }
- else{
- upper = half;
- }
- half = (lower + upper) / 2;
- ++itr_count;
- if(itr_count >= itr_max){
- throw runtime_error("Function bisect: Max iteration reached without convergence");
- }
- } while(abs(res) > tolerance);
- return bs_res;
- }
- // calculate the error given the expected result
- // 0 as expected result is a pain tho
- double calc_error(double expected_result, double experimental_result){
- double err = (expected_result - experimental_result) / expected_result;
- err = err * 100;
- return err;
- }
- int main()
- {
- //------------------ user inputs --------------------------------------
- // define the search interval
- double lower = 0, upper = 2.0;
- //------------------ algorithm starts --------------------------------------
- BisectResult br;
- for(double tolerance = 0.1; tolerance >= 0.00000001; tolerance/=10){
- cout << "------------------------------" << endl;
- cout << "tolerance: " << tolerance << endl;
- br = bisect(lower, upper, tolerance, f);
- cout << "iterations: " << br.itr_count << " result: " << br.result << endl;
- cout << "error: " << calc_error(sqrt(2), br.result) << "%" << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment