If you build and run the code, you will see it doesn't work properly.This question from a book(Problem solving and program design in C).It gives 2 equation and wants find approximating area under a curve.And adds call traps with values for n of 2, 4,8, 16, 32, 64, 128.
Output of my code is negative and -nan. Equations are:
g(x) = x^2sinx (a = 0, b = 3.14159)
h(x) = sqrt(4-pow(x.2)) ( a =-2, b=2);
And the code is:
#include <stdio.h>
#include <math.h>
void t开发者_如何转开发rap(double a,double b, int n, double *areag, double *areah);
double g(double x);
double h(double x);
int main(void)
{
double areag = 0.0, areah = 0.0;
double a1 = 0, b1 = 10;
int n;
for(n=2;n<=128;n*=2){
trap(a1, b1, n, &areag, &areah);
printf("%f %f\n", areag, areah);
}
return(0);
}
double g(double x){
return(pow(x,2)*sin(x));
}
double h(double x){
return(sqrt(4-pow(x,2)));
}
void trap(double a,double b, int n, double *areag, double *areah){
int i, l;
*areag = (b-a)/2*n * ( g(a) + g(b));
for(i = 1; i<=n-1;i++)
*areag += 2*g(i);
*areah = (b-a)/2*n * ( h(a) + h(b));
for(l=1;l<=n-1;l++)
*areah += 2*h(i);
}
I'm not sure what's intended, because you didn't explain how it is supposed to work, but this part is taking the square root of negative numbers:
sqrt(4-pow(x,2))
Ah, now I see that is the function you want to integrate. The problem is that you need to divide the range of integration into small pieces, rather than integrating over a wider range. Try
*areah += 2*h( (double) i / n);
精彩评论