Advertisement
UF6

MTH 361 Numerical Analysis

UF6
Nov 20th, 2020 (edited)
1,160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.75 KB | None | 0 0
  1. %Calculate, by hand, the integral ^1 _0 ex dx using the midpoint, trapezoidal, and Simpson’s rules and
  2. %3 subintervals. Use the error formula provided in class to estimate the minimum number m
  3. %of subintervals that are needed for computing I(f) up to an absolute error ≤ 5 · 10−4 using the
  4. %composite trapezoidal rule. Evaluate the absolute error that is actually made by coding it up.
  5.  
  6. % All of these functions must be saved as separate files in order to work.
  7.  
  8. % The Mid-Point Method
  9. function ft = Method(f,a,b,n)
  10.  
  11. h = (b-a)/n;
  12.  
  13. S =0;
  14.  
  15. x = a+0.5*h;
  16.  
  17. for i =1:n
  18.  
  19. S =S+f(x);
  20.  
  21. x = x+h;
  22.  
  23. end
  24.  
  25. ft = h*S;
  26.  
  27. end
  28.  
  29. %Simposons_3 rule
  30.  
  31. function s = Simpson_3(f, a, b, n)
  32.  
  33. % The sample vector will be...
  34.  
  35. h = (b-a)./n;
  36.  
  37. xi = a:h:b;
  38.  
  39.  
  40.  
  41. fa = f(xi(1));
  42.  
  43. fb = f(xi(end));
  44.  
  45. % The even terms like f(x2), f(x4), ect...
  46.  
  47. feven = f(xi(3:2:end-2));
  48.  
  49. % Similarly, the odd terms like f(x1), f(x3), etc...
  50.  
  51. fodd = f(xi(2:2:end));
  52.  
  53. % Bringing everything together.
  54.  
  55. s = h / 3 * (fa + 2 * sum(feven) + 4 * sum(fodd) + fb);
  56.  
  57. end
  58.  
  59. % Trapezoidal Rule
  60.  
  61. function integral = Trap(a,b,n,f)
  62.  
  63. % f= Defined function using symstems.
  64.  
  65. % a= Initial point of integral.
  66.  
  67. % b= Last point of the interval.
  68.  
  69. % n= Number of sub-intervals must be the integer.
  70.  
  71. % Examples:
  72.  
  73. % syms x
  74.  
  75. % fun = x^2+x+1
  76.  
  77. % a = 0
  78.  
  79. % b = 1.6180
  80.  
  81. % n = 100
  82.  
  83. % result = trap(a, b, n, fun)
  84.  
  85.  
  86.  
  87. result=0;
  88.  
  89. f= inline(f);
  90.  
  91. h = (b-a)/n; %Finding the space between each subintervals.
  92.  
  93. x = [a+h:h:b-h]; %Finding the mid-points of each subintervals.
  94.  
  95. for i=1:n-1
  96.  
  97. result =result+f(x(i));
  98.  
  99. end
  100.  
  101. result=h*(result+0.5*(f(a)+f(b)));
  102.  
  103. integral=result;
  104.  
  105. end
  106. % Inputs in the command window.
  107. % f=@(x) exp(x);
  108. % Method(f,0,1,8)
  109. % Simpson_3(f,0,1,8)
  110. % Trap(0,1,8,f)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement