Finding the roots of a function with c++

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.

Here what I have so far.

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
#include <iostream>
#include <cmath>
using namespace std;

int main()
{

	long double 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



Last edited on
} while ( n < i && t < abs(something) );
Topic archived. No new replies allowed.