%% Annotated Matlab transcript -- 2/13 %% CS 323 - Doug DeCarlo % We define a function f(x) like this: >> type f.m function value = f(x) value = x.^5 - 0.5; end % And we can just use it as follows: % (since we used .^ above, it can operate on vectors) >> x = 0:0.01:1; >> plot(x,f(x)) % Here we plot it with x=0 so we can see the root (around 0.9) >> plot(x,f(x),x,0) % The root is actually: >> (1/2)^(1/5) ans = 0.87055056329612 % Now we write a simple version of bisection that calls f directly: % we pass in the interval [a,b] and epsilon value >> type bisect.m function c = bisect(a, b, ep) c=(a+b)/2; while (b-c >= ep) if sign(f(b))*sign(f(c)) <= 0 a=c; else b=c; end c=(a+b)/2; end % Let's use the interval [0,1] as there is a zero crossing there % and try different epsilons: >> bisect(0,1,0.1) ans = 0.81250000000000 >> bisect(0,1,0.01) ans = 0.86718750000000 >> bisect(0,1,0.001) ans = 0.87011718750000 >> bisect(0,1,0.0001) ans = 0.87054443359375 >> bisect(0,1,0.1e-5) ans = 0.87055110931396 >> bisect(0,1,0.1e-12) ans = 0.87055056329615