1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

//Nick Barry
//Homework 9
//12/2/19
//This code will find the root of a function between two points
#include <iostream>
#include <iomanip>
using namespace std;
double bisect(double f(double x), double a, double b, double precision);
// POST: return approximate root of f between a and b
double f(double x);
// POST: function to be passed to bisect: x^3  2x  3
int main()
{
double root; // root of f() between a and b
cout.setf(ios::fixed  ios::showpoint); // set up output for fixed point with 10 decimals
cout.precision(15);
cout << "Bisection by Nick Barry\n\n";
cout << "Trace of calls\n";
cout << setw(20) << "a" << setw(20) << "m" << setw(20) << "b" << endl;
root = bisect(f, 1.0, 2.0, 1.0e15); // find root of f between 1.0 and 2.0 with tolerance 10^15
cout << "\nThe root of x^3  2x  3 between 1 and 2 is approximately " << root << endl << endl;
return 0;
}
double bisect(double f(double x), double a, double b, double precision)
// POST: return approximate root of f between a and b
{
double m;
m=(a+b)/2;//finds the midpoint of two values and sets it to m
cout << setw(20) << a << setw(20) << m << setw(20) << b << endl;
if (m==0) return m;//if midpoint is zero then root has been found
else if (ba<precision){//when precision is met return the midpoint
return m;
}
else if (f(a)*f(m)<0) bisect(f, a, m, precision);//if result is equation is less than zero then root must be between the two points
//so call function again with m replacing a or b
else if (f(m)*f(b)<0) bisect(f, m, b, precision);
return 0.0;
}
double f(double x)
// POST: function to be passed to bisect: x^3  2x  3
{
return x*x*x  2.0*x  3.0;
}
 