Advertisement
Guest User

Untitled

a guest
Apr 26th, 2020
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<math.h>
  3. #include<stdlib.h>
  4.  
  5. // functions to integrate
  6. double f1(double x){
  7. return sqrt(x);
  8. }
  9.  
  10. double f2(double x){
  11. return log(x);
  12. }
  13.  
  14. double f3(double x){
  15. return exp(x);
  16. }
  17. double f4(double x){
  18. return x*x;
  19. }
  20.  
  21. double f5(double x){
  22. return x*x*x;
  23. }
  24.  
  25. double trapeze(double (*f)(double),double a, double b, int n){
  26.  
  27. double h = (b-a)/(double)n;
  28.  
  29. double x = a;
  30. double x_next = x + h;
  31. double A;
  32. double I = 0;
  33. int i;
  34. for(i = 1; i<=n; i++){
  35. A = (h/2) * ( f(x) + f(x_next) ); // Trapezoidal area
  36. x = x + h;
  37. x_next = x + h;
  38.  
  39. I = I + A; // sum up the areas to get the integral
  40. }
  41.  
  42. return I;
  43. }
  44.  
  45. int main(){
  46.  
  47. double a,b; // integral limits
  48. int n; // number of points
  49. double I1,I2,I3,I4,I5; // values for the different integrals
  50.  
  51. a = 0;
  52. b = 1;
  53. n = 100;
  54.  
  55. I1 = trapeze(f1,a,b,n);
  56. I2 = trapeze(f2,a,b,n);
  57. I3 = trapeze(f3,a,b,n);
  58. I4 = trapeze(f4,a,b,n);
  59. I5 = trapeze(f5,a,b,n);
  60.  
  61. printf("\nIntegral of f(x) = sqrt(x) using %d points on [%0.2f %0.2f] is %0.4f",n,a,b,I1);
  62. a=0.01;
  63. printf("\nIntegral of f(x) = ln(x) using %d points on [%0.2f %0.2f] is %0.4f",n,a,b,I2);
  64. a=0;
  65. printf("\nIntegral of f(x) = exp(x) using %d points on [%0.2f %0.2f] is %0.4f",n,a,b,I3);
  66. printf("\nIntegral of f(x) = x^2 using %d points on [%0.2f %0.2f] is %0.4f",n,a,b,I4);
  67. printf("\nIntegral of f(x) = x^3 using %d points on [%0.2f %0.2f] is %0.4f",n,a,b,I5);
  68.  
  69.  
  70. return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement