Advertisement
R0qUuYdE2L9B0P

Simpson's Rule Integration

Dec 15th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. function I = simpson(a,b,N)
  2.  
  3. % This function numerically integrates a function f(x), defined in the
  4. % function "f.m"
  5.  
  6. % It takes input a = lower bound of integration, b = upper bound of
  7. % integration, N = number of "rectangles" we are finding the area of
  8.  
  9. sum_simp = 0; % initializing the sum of the Simpson terms
  10. dx = (b-a)/(N); % the step between sections
  11.  
  12. for r = 1:N+1 % there are N sections (rectangles), and so there are N+1 points
  13.  
  14. X = a + ((r-1)*dx); % each point expressed in terms of a, r and dx
  15. Y = f(X); % the function we are integrating
  16.  
  17. if (mod(r,2) == 0) % essentially, "if r is even"
  18. coeff = 4; % setting the coefficient of all "even" terms to 4 (as per Simpson's 1/3 rule)
  19. else % "if r is not even"
  20. coeff = 2; % setting the coefficient of all "odd" terms to 2 (as per Simpson's 1/3 rule)
  21. end
  22. if (r == 1)||(r == N+1) % setting the coefficient of the first and last term to 1 (as per Simpson's 1/3 rule)
  23. coeff = 1;
  24. end
  25.  
  26. sum_simp = sum_simp + (coeff*Y*dx*(1/3)); % adding each Simpson term to reach the final result
  27. end
  28. I = sum_simp; % the final output
  29.  
  30. disp(' '); disp('q1b)')
  31. disp(strcat('The integral using Simpsons rule = ', num2str(I))); % displays the result
  32. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement