Simpson's Rule

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

Below are the code i tried to and it doesn't run .....


#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, sum1 = 0, S, E, L = 1.640533; /* L is exact value of the given integration */
double x[n+1],y[n+1];

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



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

return 0 ;

}






Last edited on
What is the value of n at the point when you declare your arrays x[] and y[] of size n+1?

Actually:
(a) this statement is illegal in standard c++, as the array size is not a compile-time constant;
(b) you don't need arrays anyway. Just call your function when you need to add values to the sum.

There are plenty of other errors from a numerical-integration perspective, including the fact that you don't reinitialise sum1 as 0 for each value of n, your loops are incorrectly nested, etc. However, it will be well-nigh impossible to sort this out unless you PUT YOUR CODE IN CODE TAGS.
Last edited on
To: lastchance (1928)

i have put my code in code tags , so please have look once .
Thanks in Advance.
Danjes wrote:
i have put my code in code tags

Well, at the time of writing this, your code is not in code tags.
i have posted code in new window . Here is the website link:

http://www.cplusplus.com/forum/beginner/235798/

Danjes wrote:
i have posted code in new window


In future, please don't. It completely confuses everything if you start a new thread.

Please green-tick this thread as completed and continue on the other thread.
Topic archived. No new replies allowed.