Code for Lecture 4 + 5

# Code for Lecture 4 + 5 - format long c = f(a d = f(b if...

This preview shows pages 1–5. Sign up to view the full content.

4.1) format long r = .999; % ***Set to either .5 or .999 Snew = 0; % start sum at 0 Sold = -1; % set Sold to trick while the first time i = 0; % count iterations while Snew > Sold % is the sum still changing? Sold = Snew; % save previous value to compare to Snew = Snew + r^i; i=i+1; end - New line Snew % prints the final value. i % prints the # of iterations. >> l4p1 Snew = 2 i = 55 >> l4p1 Snew = 9.999999999999506e+002 i = 30485 The program returns the value of Snew above in 30,485 steps. The answer should be exactly 1,000. MATLab is off by: >> 1000 - Snew ans = 4.945377440890297e-011

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
5.1) function [x e] = mybisect(f,a,b,tol) % function [x e] = mybisect(f,a,b,n) % Does n iterations of the bisection method for a function f % Inputs: f -- an inline function % a,b -- left and right edges of the interval % n -- the number of bisections to do. % Outputs: x -- the estimated solution of f(x) = 0 % *****New Code**** n=1; while b-a>tol*2^(n+1) n=n+1 end % **************** % e -- an upper bound on the error

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: format long c = f(a); d = f(b); if c*d > 0.0 error( 'Function has same sign at both endpoints.' ) end disp( ' x y' ) for i = 1:n x = (a + b)/2; y = f(x); disp([ x y]) if y == 0.0 % solved the equation exactly e = 0; break % jumps out of the for loop end if c*y < 0 b=x; else a=x; end end e = (b-a)/2; >> f = inline('2*x^3 + 3*x - 1','x') f = Inline function: f(x) = 2*x^3 + 3*x – 1 >> l5p1mybisect(f,0,10,1) n = 2 n = 3 x y 5 264 2.500000000000000 37.750000000000000 1.250000000000000 6.656250000000000 ans = 1.250000000000000and given the entry below we need to be within 1.0 of the correct answer >> l5p1mybisect(f,0,10,1) n = 2 n = 3 x y 5 264 2.500000000000000 37.750000000000000 1.250000000000000 6.656250000000000 ans = 1.250000000000000 Subtract MATLab from real answer to confirm the answer is within the tolerance. >> 1.25-0.3129084 ans = 0.937091600000000 The error is less than 1...
View Full Document

{[ snackBarMessage ]}

### Page1 / 5

Code for Lecture 4 + 5 - format long c = f(a d = f(b if...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online