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
55
56
57
58
59
60
|
#include <stdio.h> /* Header for input/output subroutines. */
#include <math.h> /* Header for math subroutines. */
#include <float.h> /* Header for floating point subroutines. */
#define pi 3.141592653589793238462643383279 /* Accurate value for pi. */
/* Simpson's rule for approximating integrals.
a: left endpoint
b: right endpoint
fc: pointer to function to integrate
n: number of subintervals
*/
double fc (double x);
main()
{
double a,b,h,sum,x,y; /* In 'C' all variables must be assigned */
double p1, p2, p3;
int i, n;
printf("\007"); /* Sound bell in computer. */
a = (double) 0.0;
printf("\nLeft end point = %.16lf",a);
b = (double) pi;
printf("\nRight end point = %.16lf",b);
i = -1;
while (i < 0){
printf("\nEnter number of subintervals (must be even) ");
scanf("%d",&n);
i = n/2; i = 2*i - n; /* Don't allow odd values of n. */
if (n<=0) i = -1; /* Don't allow zero or negative. */
}
printf("\nNumber of subintervals %d",n);
h = (double) (b-a)/n;
for (i=1, sum=0.0; i<=n; i = i+ 2){
p1 = fc((double) a+(i-1)*h);
p2 = fc((double) a+i*h);
p3 = fc((double) a+(i+1)*h);
sum += p1 + 4.0 * p2 + p3;
/* printf("\n x, f(x) %.16lf %.16lf",a+(i-1)*h,p1); */
/* printf("\n x, f(x) %.16lf %.16lf",a+i*h,p2); */
/* printf("\n x, f(x) %.16lf %.16lf",a+(i+1)*h,p3); */
}
printf("\nValue of sum = %.16lf", (double) sum);
y = (double) h*sum/3.0;
printf("\nValue of integral = %.16lf", (double) y);
/* x=(double) 2.0; */
printf("\nTheoretical Value = %.16lf", (double) 2.0*sqrt(2.0)*1.35064388);
printf("\n");
return(0);
}
double fc (double x)
{
double y;
y = (double) sqrt(1.0+cos(x)*cos(x));
return (y);
}
/* End of file */
|