Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %Calculate, by hand, the integral ^1 _0 ex dx using the midpoint, trapezoidal, and Simpson’s rules and
- %3 subintervals. Use the error formula provided in class to estimate the minimum number m
- %of subintervals that are needed for computing I(f) up to an absolute error ≤ 5 · 10−4 using the
- %composite trapezoidal rule. Evaluate the absolute error that is actually made by coding it up.
- % All of these functions must be saved as separate files in order to work.
- % The Mid-Point Method
- function ft = Method(f,a,b,n)
- h = (b-a)/n;
- S =0;
- x = a+0.5*h;
- for i =1:n
- S =S+f(x);
- x = x+h;
- end
- ft = h*S;
- end
- %Simposons_3 rule
- function s = Simpson_3(f, a, b, n)
- % The sample vector will be...
- h = (b-a)./n;
- xi = a:h:b;
- fa = f(xi(1));
- fb = f(xi(end));
- % The even terms like f(x2), f(x4), ect...
- feven = f(xi(3:2:end-2));
- % Similarly, the odd terms like f(x1), f(x3), etc...
- fodd = f(xi(2:2:end));
- % Bringing everything together.
- s = h / 3 * (fa + 2 * sum(feven) + 4 * sum(fodd) + fb);
- end
- % Trapezoidal Rule
- function integral = Trap(a,b,n,f)
- % f= Defined function using symstems.
- % a= Initial point of integral.
- % b= Last point of the interval.
- % n= Number of sub-intervals must be the integer.
- % Examples:
- % syms x
- % fun = x^2+x+1
- % a = 0
- % b = 1.6180
- % n = 100
- % result = trap(a, b, n, fun)
- result=0;
- f= inline(f);
- h = (b-a)/n; %Finding the space between each subintervals.
- x = [a+h:h:b-h]; %Finding the mid-points of each subintervals.
- for i=1:n-1
- result =result+f(x(i));
- end
- result=h*(result+0.5*(f(a)+f(b)));
- integral=result;
- end
- % Inputs in the command window.
- % f=@(x) exp(x);
- % Method(f,0,1,8)
- % Simpson_3(f,0,1,8)
- % Trap(0,1,8,f)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement