One of the
applications of computers in numerical analysis is computing the area under a
curve. One simple method of calculating
the area under a curve is to divide the area into a number of trapezoids of same
width and summing up the area of individual trapezoids. The area of a trapezoid is given by
Area
= 0.5 * (h1 + h2) * b
The program in Fig 9.20 calculates the area
for a curve of the function
f(x)
= x2 + 1
between any two given limits, say, A and B.
Input
Lower limit
(A)
Upper limit
(B)
Number of trapezoids
Output
Total area under the curve between the
given limits.
Algorithm
1.
Input the lower and upper
limits and the number of trapezoids.
2.
Calculate the width of
trapezoids.
3.
Initialize the total area.
4.
Calculate the area of trapezoid
and add to the total area.
5.
Repeat step-4 until all the
trapezoids are completed.
6.
Print total area.
The evaluation
of f(x) has been done using a separate function so that it can be easily
modified to allow other functions to be evaluated.
The output for
two runs shows that better accuracy is achieved with larger number of
trapezoids. The actual area for the
limits 0 and 3 is 12 units (by analytical method)
AREA UNDER A CURVE
Program
#include <stdio.h>
float start_point, /*
GLOBAL VARIABLES */
end_point,
total_area;
int numtraps;
main( )
{
void input(void);
float find_area(float
a,float b,int n); /* prototype */
print(“AREA UNDER A CURVE”);
input( );
total_area = find_area(start_point,
end_point, numtraps);
printf(“TOTAL AREA = %f”, total_area);
}
void
input(void)
{
printf(“\n Enter lower limit:”);
scanf(“%f”, &start_point);
printf(“Enter upper limit:”);
scanf(“%f”, &end_point);
printf(“Enter number of trapezoids:”);
scanf(“%d”, &numtraps);
}
float
find_area(float a, float b, int n)
{
float
base, lower, h1, h2; /* LOCAL VARIABLES */
float
function_x(float x); /* prototype */
float
trap_area(float h1,float h2,float base);/*prototype*/
base = (b-1)/n;
lower = a;
for(lower =a; lower <= b-base; lower
= lower + base)
{
h1
= function_x(lower);
h1 =
function_x(lower + base);
total_area
+= trap_area(h1, h2, base);
}
return(total_area);
float trap_area(float height_1,float
height_2,float base)
{
float area; /* LOCAL VARIABLE */
area = 0.5 * (height_1 + height_2) * base;
return(area);
}
float function_x(float x)
{
/* F(X) = X * X + 1 */
return(x*x + 1);
}
Output
AREA UNDER A CURVE
Enter lower limit: 0
Enter upper limit: 3
Enter number of trapezoids: 30
TOTAL AREA =
12.005000
AREA UNDER A CURVE
Enter lower limit: 0
Enter upper limit: 3
Enter number of trapezoids: 100
TOTAL AREA = 12.000438
No comments:
Post a Comment