Looping untill absolute value is small enough

Okay so I'm making a program were I am measuring the approximated value of the area under a function. I'm making it so that I write the limits and then an error value that I allow. I choose the value. This means that the problem should terminate when fabs(SumOld-sum) < eps. And also to show at how many intervals under the graph of the functions this is achieved. The problem is that I can't make it work. If I type in the error as 0.00000001 I should get a sum around 8.999999998 if the limits are 0 and 3 and intervals at 32768, but I get a totally different i. e. wrong number.. I so far have the following

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
  #include <iostream>
#include <math.h>
#include <iomanip>
#include <cmath>
#include <stdlib.h>
using namespace std;

double f(double x);


int main(){

		double sum,SumOld,x,eps,dx,a,b;
		int n;

		cout<<"\n a";
		cin>>a;

		cout<<"\n b";
		cin>>b;

		cout<<"\n Error";
		cin>>eps;

		n=1;
		sum=0;

		do
				{
			sum=0;
					x=a-(dx/2);
					dx=(b-a)/n;
					SumOld=sum;
						x=x+dx;
						n=2*n;
						sum=sum+f( x )*dx;

}

				while(fabs(SumOld-sum) < eps);
		cout<<"\n The integral is approximated to "<<sum <<" with a middlesum of"<<n/2<<" intervals";
				return 0;
}

double f(double x)

{
	double resultat;
				resultat=x*x;
				return resultat;
}
Last edited on
I don't see a question.
Oh I'm sorry. The problem is that I can't make it work. If I type in the error as 0.00000001 I should get a sum around 8.999999998 and intervals at 32768, but I get a totally different i. e. wrong number.
closed account (48T7M4Gy)
http://www.cplusplus.com/forum/beginner/175116/
http://www.cplusplus.com/forum/beginner/174901/
Last edited on
Topic archived. No new replies allowed.