Advertisement
tampurus

Unit 4.1 Trapezoidal Integration

Apr 21st, 2022 (edited)
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.19 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3. #define f(x) (sin(x)-log(x)+exp(x)) //1.4 0.2 0.1
  4. // #define f(x) x*x*x*x //3 -3 1
  5.  
  6. int main()
  7. {
  8.     float b,a,h,x[20],sum=0;
  9.     int n;
  10.     printf("Enter the values of upper limit,lower limit and h\n");
  11.     scanf("%f %f %f",&b,&a,&h);
  12.    
  13.     n = ceil(((b-a)/h));
  14.    
  15.     for(int i=0 ; i<=n ; i++){
  16.         x[i] = a+ (i*h);
  17.     }
  18.     for(int i=1 ; i<n ; i++){
  19.         sum += f(x[i]);
  20.     }
  21.    
  22.     float ans = (h/2) * ( f(x[0]) + f(x[n]) + (2*sum) ) ;
  23.     printf ("\nFinal answer is %f",ans);
  24.  
  25.     return 0;
  26. }
  27. /*
  28. Output 1
  29. Enter the values of upper limit,lower limit and h
  30. 1.4 .2 .1
  31.  
  32. Final answer is 4.056173
  33.  
  34. Output 2
  35. Enter the values of upper limit,lower limit and h
  36. 3 -3 1
  37. Final answer is 115.000000
  38. */
  39.  
  40.  
  41.  
  42. Algo
  43.  
  44. define function
  45. read a,b and h , where a lower , b upper limit and h size of interval
  46. n = (b-a)/h + 1
  47. declare float array x of size of n
  48.  
  49. start a loop from i=0 to n-1
  50.     x[i] = a + (i*h)
  51. end i loop
  52.    
  53. calulate sum of all ordinates excluding extreme
  54. declare sum = 0
  55.     start loop from i=1 to n-2
  56.         sum = sum + f(x[i])
  57.     end loop i
  58.  
  59. ans = h/2 * ( f(x[0]) + f(x[n-1]) + (2*sum)
  60.  
  61. print ans
  62. stop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement