Professional Documents
Culture Documents
CE 335
Prof. Krakauer
H.W. # 2
%3.1 - Bisection Method
a=1;
b=2;
n=5; %5 iterations
fa = a^4-2;
fb = b^4-2;
if fa*fb > 0
error('Function has same sign at both endpoints a and b.')
end
disp(' x f(x) abs_error frac_error')
for i = 1:n
c = (a + b)/2;
fc = c^4-2;
abs_error=abs(c-(sqrt(2))); %absolule error
frac_error= abs_error/(sqrt(2)); %fractional error
for i=1:n
c=(b*fa-a*fb)/(fa-fb);
fc=c^4-2;
abs_error=abs(c-(sqrt(2)));
frac_error= abs_error/(sqrt(2));
if fa*fc==0
return %not helpful in finding roots, since product is zero
end;
if fa*fc >0
a=c;
else
if fa*fc <0
b=c;
end
end
end
Output:
function [c] = falsepos( a,b,n )
format long
format compact
a=1;
b=2;
n=5; %number of iterations are not specified, I chose 5
fa=a^4-2;
fb=b^4-2;
if fa*fb > 0
error('Function has same sign at both endpoints a and b.')
end
disp(' x f(x) abs_error frac_error')
for i=1:n
c=(b*fa-a*fb)/(fa-fb);
fc=c^4-2;
abs_error=abs(c-(sqrt(sqrt(2))));
frac_error= abs_error/(sqrt(sqrt(2)));
disp([ c fc abs_error frac_error ])
if fa*fc==0
return
end;
if fa*fc >0
a=c;
else
if fa*fc <0
b=c;
end
end
end
Output:
function [c] = secant_while(a,b, tol)
format long
format compact
a=1;
b=2;
tol= input('What is the tolerance?')
fa = a^4-2;
fb = b^4-2;
abs_error= 1;
disp(' x f(x) absolute_error
fractional_error')
while abs_error > tol
s =(fb - fa)/(b - a); %the estimation of the slope
c = b - fb/s; % secant formula.
fc = c^4-2; % function at the new approximate solution.
abs_error=abs(c-(sqrt(2))); %absolule error
frac_error= abs_error/(sqrt(2)); %fractional error
disp([c fc abs_error frac_error])
a = b;
fa = fb;
b = c;
fb = fc;
end
Output:
Output:
%4.3 %5 50 100 150 200 300 400 500
A= zeros(5,5);
for i1 = 1:5,
A(:,i1) = (randperm(5));
end
B = zeros(50,50);
for i2 = 1:50,
B(:,i2) = (randperm(50));
end
C = zeros(100,100);
for i3 = 1:100,
C(:,i3) = (randperm(100));
end
D = zeros(150,150);
for i4 = 1:150,
D(:,i4) = (randperm(150));
end
E = zeros(200,200);
for i5 = 1:200,
E(:,i5) = (randperm(200));
end
F = zeros(300,300);
for i6 = 1:300,
F(:,i6) = (randperm(300));
end
G = zeros(400,400);
for i7 = 1:400,
G(:,i7) = (randperm(400));
end
H = zeros(500,500);
for i8 = 1:500,
H(:,i8) = (randperm(500));
end
tic
inv(A)
timeneededA = toc
tic
inv(B)
timeneededB = toc
tic
inv(C)
timeneededC = toc
tic
inv(D)
timeneededD = toc
tic
inv(E)
timeneededE = toc
tic
inv(F)
timeneededF = toc
tic
inv(G)
timeneededG = toc
tic
inv(H)
timeneededH = toc
Output: