Advertisement
tampurus

Unit 4.2 Simpson's 1/3 Integration

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