-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
trap.c
73 lines (61 loc) · 1.79 KB
/
trap.c
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
61
62
63
64
65
66
67
68
69
70
71
72
73
/* File: trap.c
* Purpose: Calculate definite integral using trapezoidal
* rule.
*
* Input: a, b, n
* Output: Estimate of integral from a to b of f(x)
* using n trapezoids.
*
* Compile: gcc -g -Wall -o trap trap.c
* Usage: ./trap
*
* Note: The function f(x) is hardwired.
*
* IPP: Section 3.2.1 (pp. 94 and ff.) and 5.2 (p. 216)
*/
#include <stdio.h>
double f(double x); /* Function we're integrating */
double Trap(double a, double b, int n, double h);
int main(void) {
double integral; /* Store result in integral */
double a, b; /* Left and right endpoints */
int n; /* Number of trapezoids */
double h; /* Height of trapezoids */
printf("Enter a, b, and n\n");
scanf("%lf", &a);
scanf("%lf", &b);
scanf("%d", &n);
h = (b-a)/n;
integral = Trap(a, b, n, h);
printf("With n = %d trapezoids, our estimate\n", n);
printf("of the integral from %f to %f = %.15f\n",
a, b, integral);
return 0;
} /* main */
/*------------------------------------------------------------------
* Function: Trap
* Purpose: Estimate integral from a to b of f using trap rule and
* n trapezoids
* Input args: a, b, n, h
* Return val: Estimate of the integral
*/
double Trap(double a, double b, int n, double h) {
double integral;
int k;
integral = (f(a) + f(b))/2.0;
for (k = 1; k <= n-1; k++) {
integral += f(a+k*h);
}
integral = integral*h;
return integral;
} /* Trap */
/*------------------------------------------------------------------
* Function: f
* Purpose: Compute value of function to be integrated
* Input args: x
*/
double f(double x) {
double return_val;
return_val = x*x;
return return_val;
} /* f */