I have to create a program that will find the roots of a function using Newtons method. I have the code done for the most part but I cant find out what to put for my conditions to the loop. The program is suppose to stop running once the tolerance provided is reached or the maximum iterations is reached. So far I've got it stop when maximum iterations are reached but could use some help with the tolerance part.
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
longdouble a,b,t,i,a1,b1,n,x,x1;
cout<<"This program computes the roots of f(x)= x^3 + x - 0.5cos(x)."<<endl<<endl;
cout<<"Please enter the interval to search for the root."<<endl<<"a b:";
cin>>a>>b;
if(b <= a)
{
cout<<"b should be greater than a."<<endl;
return 0;
}
cout<<"Please enter the error tolerance: ";
cin>>t;
if(t <= 0)
{
cout<<"Positive error and iterations requited."<<endl;
return 0;
}
cout<<"Please enter the maxium number of iterations for the search: ";
cin>>i;
a1=pow(a,3)+a-(0.5*(cos(a)));
b1=pow(b,3)+b-(0.5*(cos(b)));
if(a1*b1<0)
{
cout<<"No sign change, root may not exist.";
}
x= (a+b)/2;
n=0;
do
{
x1=0;
n++;
x1= x-(pow(x,3)+x-(0.5*(cos(x))))/(3*pow(x,2)+1+(0.5*(sin(x))));
cout<<"n= "<<n<<" x= "<<x1<<endl;
x=x1;
} while (n<i);
return 0;
}
Heres an example of what the program should do when working.
Example:
This program computes the roots of f(x) = x^3 +x - 0.5cos(x).
Please enter the interval to search for the root.
a b: 10 20
Please enter the error tolerance: 0.00001
Please enter the maximum number of iterations for the search: 250
No sign change, root may not exist.
n = 1 x = 9.98706
n = 2 x = 6.63147
n = 3 x = 4.39413
n = 4 x = 2.86473
n = 5 x = 1.82206
n = 6 x = 1.1234
n = 7 x = 0.679464
n = 8 x = 0.455621
n = 9 x = 0.400699
n = 10 x = 0.397931
n = 11 x = 0.397925
n = 12 x = 0.397925