/************************* Program 2.5 ****************************/ /* */ /************************************************************************/ /* Please Note: */ /* */ /* (1) This computer program is written by Tao Pang in conjunction with */ /* his book, "An Introduction to Computational Physics," published */ /* by Cambridge University Press in 1997. */ /* */ /* (2) No warranties, express or implied, are made for this program. */ /* */ /************************************************************************/ #include #include #define NMAX 12 main() /* Main program for evaluation of an integral with integrand sin(x) in the region of [0,pi/2]. Copyright (c) Tao Pang 1997. */ { int i,n; double pi,h,s; double x[NMAX],f[NMAX]; void simp(); n = NMAX; pi = 4.0*atan(1.0); h = pi/(2*(n-1)); for (i = 0; i < n; ++i) { x[i] = h*i; f[i] = sin(x[i]); } simp (n,h,f,&s); printf("%16.8lf\n",s); } void simp (n,h,f,s) /* Subroutine for integration over f(x) with the Simpson rule. f: integrand f(x); h: interval; s: integral. Copyright (c) Tao Pang 1997. */ int n; double h,*s; double f[]; { int i; double s0,s1,s2; s0 = 0; s1 = 0; s2 = 0; for (i = 1; i < n-1; i = i+2) { s0 = s0+f[i]; s1 = s1+f[i-1]; s2 = s2+f[i+1]; } *s = h*(s1+4*s0+s2)/3; /* If n is even, add the last slice separately */ if (n%2 == 0) *s = *s+h*(5*f[n-1]+8*f[n-2]-f[n-3])/12; }