Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<math.h>
- #include<stdlib.h>
- // functions to integrate
- double f1(double x){
- return sqrt(x);
- }
- double f2(double x){
- return log(x);
- }
- double f3(double x){
- return exp(x);
- }
- double f4(double x){
- return x*x;
- }
- double f5(double x){
- return x*x*x;
- }
- double trapeze(double (*f)(double),double a, double b, int n){
- double h = (b-a)/(double)n;
- double x = a;
- double x_next = x + h;
- double A;
- double I = 0;
- int i;
- for(i = 1; i<=n; i++){
- A = (h/2) * ( f(x) + f(x_next) ); // Trapezoidal area
- x = x + h;
- x_next = x + h;
- I = I + A; // sum up the areas to get the integral
- }
- return I;
- }
- int main(){
- double a,b; // integral limits
- int n; // number of points
- double I1,I2,I3,I4,I5; // values for the different integrals
- a = 0;
- b = 1;
- n = 100;
- I1 = trapeze(f1,a,b,n);
- I2 = trapeze(f2,a,b,n);
- I3 = trapeze(f3,a,b,n);
- I4 = trapeze(f4,a,b,n);
- I5 = trapeze(f5,a,b,n);
- printf("\nIntegral of f(x) = sqrt(x) using %d points on [%0.2f %0.2f] is %0.4f",n,a,b,I1);
- a=0.01;
- printf("\nIntegral of f(x) = ln(x) using %d points on [%0.2f %0.2f] is %0.4f",n,a,b,I2);
- a=0;
- printf("\nIntegral of f(x) = exp(x) using %d points on [%0.2f %0.2f] is %0.4f",n,a,b,I3);
- printf("\nIntegral of f(x) = x^2 using %d points on [%0.2f %0.2f] is %0.4f",n,a,b,I4);
- printf("\nIntegral of f(x) = x^3 using %d points on [%0.2f %0.2f] is %0.4f",n,a,b,I5);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement