Here the bisecting algorithm: Lab App 1.1 Bisection Algorithm Exercise 1 Read th
ID: 3573888 • Letter: H
Question
Here the bisecting algorithm:Lab App 1.1 Bisection Algorithm Exercise 1 Read the Bisection Algorithm handout (bisection.pd) and write a function for the algorithm that returns the answer to the calculation. The main function is responsible for reading the input parameters and writing the output. Make sure to check input for errors before calling the Bisection algorithm. Use the algorithm with the given function in the example, which you will have to code into the program as a C++ function. Follow the example given.
Explanation / Answer
#include <bits/stdc++.h>
using namespace std;
double f(double p)
{
double val=20*p*p-7*p-40; // assuming the polynomial to be this
return val;
}
double bisection(double a, double b, double tol, int n)
{
int i=1;
double p;
cout<<"i a b p fp"<<endl;
cout<<setprecision(5);
while(i<n)
{
p=a+(b-a)/2;
double val=f(p); // f(p) is valur of function at x=p
cout<<i<<" "<<a<<" "<<b<<" "<<p<<" "<<val<<endl;
if(abs(val)<1e-19 || ((b-a)/2)<tol)
return p;
i=i+1;
if(f(a)*f(p)>0)
a=p;
else b=p;
}
cout<<"Method failed after N interactions, N= "<<n<<endl;
exit(0);
}
int main()
{
double a,b,tol;
int n;
cout<<"Enter a and b surrounding solution: ";
cin>>a>>b;
if(a>b)
{
cout<<"a is greater than b";
exit(0);
}
cout<<"Enter tolerance: ";
cin>>tol;
if(tol<0)
{
cout<<"tolerance cannot be negative";
exit(0);
}
cout<<"Enter maximum number of iterations: ";
cin>>n;
double p=bisection(a,b,tol,n);
cout<<"A zero was found at p= "<<p;
return 0;
}