Simpson's Rule for nth number of interval

My objective is to estimate the numerical integral method using Simpson's rule for n numbers of interval and n = 2,4,6,8,....20) and output should be given in three columns which are n , S (Simpson's result) and E (Error)

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

#include<stdio.h>
#include <iostream>
#include<cmath>

double f(double x)
 {
 double g =(400*x*x*x*x*x -900*x*x*x*x + 675*x*x*x-200*x*x+25*x+0.2);

   return g;
}

   int main ()
{
 int i ;

long double a = 0,b = 0.8,h,n, sum , S, E, L = 1.640533; // L is exact  result value of the given function  integration 
double x[10], y[10];
double x[n],y[n];

cout <<" Given f(x)= 400x^5 -900x^4+675^x^3+ -200x^2+25x-0.2 "<<endl;



  for (n=2; n< 21;n+=2){
  for (i=0;i<n+1;i++){


    h=(b-a)/n;
    x[i]=a+i*h;
    y[i]=f(x[i]);
  }

  }

for (i=1;i<n;i+=2)
{
sum = sum+4*y[i];
}
for (i=2;i<n-1;i+=2)
{
sum1=sum1+2*y[i];
}
    S = h/3*(y[0]+y[n]+sum);
   E = ((L-S)/L)*100;



cout << "  " << n << "  " << S << "  "  << E << "     "  << endl;

 return 0 ;

 }
Please @Danjes, DON'T START A NEW THREAD ON THE SAME TOPIC - it confuses everything.

1
2
double x[10], y[10];
double x[n],y[n];

Does this not look wrong to you?
Irrespective of the C++ errors here, you do NOT need arrays at all. Please read below.


You have an n-loop enclosing an i-loop on lines 25-34. Both of these close, but you do not need this segment of code at all (except for the h=(b-a)/n; line which can be moved to later).


You need an n loop to enclose lines lines 36 to 49. It should start with the interval calculation h=(b-a)/n;. That should be followed by re-setting sum to zero for each value of n.


You are confusing sum and sum1. I think they are the same variable.


Instead of using your y-array on line 38 you can evaluate the function here - it is only used once:
sum = sum+4*f( a+i*h );
Something similar can be done on line 42.


There appears to be a minor discrepancy (+0.2 or -0.2) between the function calculated on line 8 and that stated on line 21. Only you know which is correct.


PLEASE USE CONSISTENT AND SENSIBLE INDENTATION. Look at your code in tags above.





Last edited on
Topic archived. No new replies allowed.