Answer: Problem#1
Answer: Problem#1
Answer
Function file
function [root,iter]=bisection(func,xl,xu,es,maxit,varargin)
%[root,fx,ea,iter]=bisect(func,xl,xu,es,maxit):
% input:
% output:
test = func(xl,varargin{:})*func(xu,varargin{:});
while (1)
xrold = xr;
xr = (xl + xu)/2;
iter = iter + 1;
test = func(xl,varargin{:})*func(xr,varargin{:});
if test < 0
xu = xr;
xl = xr;
else
ea = 0;
end
end
Script file
clear;
clc;
xL = -2;
xR = 0.1;
Output
The value of the root x*: -0.3222
The value of f(x*): 0.0000001355
Problem#2
Answer
Script file
clear all
f=@(x)x.^3+3*x+1
df=@(x)3*x.^2+3
while abs(f(x0))>0.00001
x1=x0-(f(x0)/df(x0))
x0=x1
end
Output file
f =
@(x) x .^ 3 + 3 * x + 1
df =
@(x) 3 * x .^ 2 + 3
Problem#3
Answer
Bisection Method
Script File
clc;
clear all;
close all;
fx=@(x) 1/2+x^2/4-x*sin(x)-cos(2*x)/2;
a=0;
b=pi;
for n=1:N
c=(a+b)/2;
f1=feval(fx,a);
f2=feval(fx,b);
f3=feval(fx,c);
b=c;
else
a=c;
end
break;
end
end
Output File
roots using bisection method is = 1.570796 with iteration 20000
f(1.570796)=0.0460540184
Newton Method
Script File
clc;
clear all;
close all;
fx=@(x) 1/2+x^2/4-x*sin(x)-cos(2*x)/2;
fdx=@(x) x/2-sin(x)+x*cos(x)+sin(2*x);
a(1,1)=pi/2;
a(2,1)=5*pi;
a(3,1)=10*pi;
%%
for m=1:3
for n=1:N
a(m,n+1)=a(m,n)-feval(fx,a(m,n))/feval(fdx,a(m,n));
k=abs(feval(fx,a(m,n+1)));
if (k<10^(-5))
break;
end
end
end
Output File
With initial guess x0=1.570796 roots is 1.891623 with iteration 440
F(1.891623)=1.000804x10^(-5)
F(1.891623)=1.000804x10^(-5)
F(-0.006724)=1.13027033x10^(-5)
Problem#4
Answer
Function File
function[r,itrr]=Bisectionf(f,xL,xR,tol)
% f=@(x)(x^2-7); %given
% fprintf('given value of a and b is not suitable for this method enter value of a and b such that
f(a)*f(b)<0');
% end
a=xL;
b=xR;
i=1;
x1=a;x=b; % just for going inside while loop for one time
while(abs(x1-x)>tol)
fprintf('iteration=%2d\n',i);
i=i+1;
x=(a+b)/2;
itter_mat=[itter_mat,x];
ERR_mat=[ERR_mat,abs(x-sqrt(2))];
fprintf('x=%2d\n',x)
if(f(x)*f(a)<0)
b=x;
else
a=x;
end
fprintf('iteration=%2d\n',i);
i=i+1;
x1=(a+b)/2;
itter_mat=[itter_mat,x1];
ERR_mat=[ERR_mat,abs(x1-sqrt(2))];
fprintf('x=%2d\n',x1)
if(f(x1)*f(a)<0)
b=x1;
else
a=x1;
end
end
r=x1;
itrr=length(itter_mat);
itter_mat
ERR_mat
plot(itter_mat)
hold on
plot(ERR_mat)
Script File
clc
syms x;
% Input Section
fb = eval(subs(y,x,b));
if fa*fb > 0
else
c = (a+b)/2;
fc = eval(subs(y,x,c));
fprintf('\n\na\t\t\tb\t\t\tc\t\t\tf(c)\n');
while abs(fc)>e
fprintf('%f\t%f\t%f\t%f\n',a,b,c,fc);
if fa*fc< 0
b =c;
else
a =c;
end
c = (a+b)/2;
fc = eval(subs(y,x,c));
end
end
Output File
Enter non-linear equations: > x^2-7
Problem#5
Answer