Integral evaluation

Hello! I'm trying to write a program to evaluate a definite integral with Simpson's composite rule.

http://picpaste.com/pics/12-GXeA9MIK.1416154254.png

I already got this far (see below), but my answer is not correct. The output of my code is equal 0.07. But answer of WolphramAlpha that uses identical algorithm is 0.439818.

http://www.wolframalpha.com/widget/widgetPopup.jsp?p=v&id=174a81e7a9ffb5aed0a790093981aaab&title=Simpson%27s%20Rule%20Calculator%20MyAlevelMathsTutor&theme=blue&i0=0.6369*sin%28sin%28x%29%29*sin%28x%29&i1=0&i2=1.57&i3=0.3925&podSelect=&podstate=SymbolicForm__Show%20details

What should I change for in my code? Any help will be appreciated.

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
  #include <iostream.h>
#include <math.h>
#include <conio.h>

using namespace std;

double f(double x) {
	return ((0.6369)*sin(sin(x))*sin(x));
}

int main() {


double a = 0.0;
double b = 1.57;
double n = 2.0;
double eps = 0.1;

double h = (b-a)/(2*n);
double s = f(a) + f(b);
int k = 1;
int x;
double i;

while (k>(2*n)-1) {
	x = a+h*k;
	s = s+4*f(x)+2*f(x+h);
	k = k+2;
	}

i = s*h/3;

cout << "integral is equal " << i;
cout << "\nPress any key to close";

getch();
return 0;
}

Last edited on
The first time the program reaches line 25 k=1, n=2 so the condition is false and the loop never executes. Should the condition be k <= 2*n-1?
Tank you so much. When I set while (k<n) in line 25, answer is equal 0.9. It's a bit better. I've found more accurate method's algorithm. Could you advice how to add condition
|i1 - i2|<eps
to program (by the following accurate scheme):

http://picpaste.com/pics/Scheme-NwfbKp49.1416165341.jpg
if i1 or i2 is a double, then use if (fabs(i1-i2) < eps) ...
Topic archived. No new replies allowed.