/************************************************************* * Program to demonstrate integration of a real function F(x) * * by Simpson's method * * ---------------------------------------------------------- * * REFERENCE: "Mathematiques en Turbo-Pascal (Part 1) By * * Marc Ducamp and Alain Reverchon, Eyrolles, * * Paris, 1987" [BIBLI 03]. * * ---------------------------------------------------------- * * SAMPLE RUN: * * (Integrate sin(x) from x=0 to x=1) * * * * Integral of a function F(X) by Simpson's method * * * * Input begin and end values for x variable: * * * * X0 = 0 * * X1 = 1 * * * * Number of integration steps: 100 * * * * * * Value of integral: 0.459698 * * * * * * C++ version by J-P Moreau. * * (www.jpmoreau.fr) * *************************************************************/ #include #include double x0, //begin x value x1; //end x value int nstep; //number of integration steps double result; //result of integral // Given function to integrate double FUNC(double x) { return sin(x); } /****************************************************** * Integral of a function FUNC(X) by Simpson's method * * --------------------------------------------------- * * INPUTS: * * a begin value of x variable * * b end value of x variable * * n number of integration steps * * * * OUTPUT: * * res the integral of FUNC(X) from a to b * * * ******************************************************/ void Integral_Simpson(double a, double b, int n, double *res) { int i; double step,r; step=(b-a)/2/n; r=FUNC(a); *res=(r+FUNC(b))/2; for (i=1; i<2*n; i++) { r=FUNC(a+i*step); if ((i%2) != 0) *res += r+r; else *res += r; } *res *= step*2/3; } void main() { printf("\n Integral of a function F(X) by Simpson's method\n\n"); printf(" Input begin and end values for x variable:\n\n"); printf(" X0 = "); scanf("%lf", &x0); printf(" X1 = "); scanf("%lf", &x1); printf("\n Number of integration steps: "); scanf("%d", &nstep); Integral_Simpson(x0,x1,nstep,&result); printf("\n\n Value of integral: %f\n\n", result); } // End of file tsimpson.cpp