You would like to find the area under the curve yfx between

You would like to find the area under the curve y=f(x) between the lines x = a and x = b. One way to approximate this area is to use line segments as approximations of small pieces of the curve and then to sum the areas of trapezoids created by drawing perpendiculars from the line segment endpoints to the x-axis, as shown in Fig. We will assume that f (x) is nonnegative over the interval [a, b]. The trapezoidal rule approximates this area T as T = h/2 (f(a) + f(b) + 2 sigma^n - 1_i = 1) for n subintervals of length h: h = b - a/n Write a function trap with input parameters a, b, n, and f that implements the trapezoidal rule. Call trap with values for n of 2, 4, 8, 16, 32, 64. and 128 on functions g (x) = x2 sin x (a = 0, b = 3.14159) and h (x) = squareroot 4 - x^2 (a = 2, b = 2) Function h defines a half-cried of radius 2. Compare your approximation to the actual area of this half-cried. fab f(x)dx

Solution


#include <stdio.h>
#include <math.h>


//Note 4th parameter in function pointer means taking address of another function as pointer

float trap(float a, float b, int n, float (*f)(float val)) {
   float h = (b-a)/n;
   float delta = f(a)+f(b);
   for(int i = 1; i < n; i++){
delta+= 2*f(a+i*h);
}
   float area=h/2*delta;
   return area;
}

float g(float x) {
   return x*x*sin(x);
}

float h(float x) {
   return sqrt(4-x*x);
}

int main() {
float a=0;
float b=3.14159;
int n=0;
for(n=0; n<8; n++){
   printf(\"value for trap for g(x) for n=%d is %f\ \",n,trap(a,b,2^n,&g));
}


a=-2;
b=2;
n=0;
for(n=0; n<8; n++){
   printf(\"value for trap for h(x) for n=%d is %f\ \",n,trap(a,b,2^n,&h));
}
printf(\"Area of a circle with radius 2 is float %f\ \",3.1459*2*2/2);

printf(\"End of Main...\ \");

}

 You would like to find the area under the curve y=f(x) between the lines x = a and x = b. One way to approximate this area is to use line segments as approxima

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site