Professional Documents
Culture Documents
BISECTION
x1=input('enter x1:');
x2=input('enter x2:'); %[a,b]
n=input('enter n:');
f= @(x) x.^2-5*x+6; %f=inline('x*x -5*x +6');
y1=f(x1);
y2=f(x2);
for i=1:n
x3=(x1+x2)/2; %c
y3=f(x3);
if abs(y3)<=0.0001
break;
end
if y1*y3<0.0
x2=x3; %b=x3, [a,x3]
y2=f(x2); % x3 inputedfor replace of b
else
x1=x3; %a=x3 , [x3,b]
y1=f(x1); %x3 inputed for replace of a
end
end
fprintf('Bisection Result is %f:\n ', x3);
ITERATION:
fun = @(x) 1/sqrt(x + 1);
root = 0;
prevRoot = input('enter initial value: ');
for i = 1:1:100
root = fun(prevRoot);
if abs(fun(root) - fun(prevRoot)) <= 0.0001
break;
else
prevRoot = root;
end
end
fprintf('ans = %f\n iteration: %d\n', root, i);
ANOTHER
f= @(x) x.^2-5*x+6;
phi=@(x) ((x.^2-6)/5);
x= 0;
choice = input('enter initial value: ');
for i = 1:1:100
x = f(choice);
if abs(phi(x) - phi(choice)) <= 0.0001
break;
else
choice = x;
end
end
fprintf('ans = %f\n-iteration: %d\n', x, i);
SECANT REGULA
f = @(x) x*x-5*x+6; %x*x*x - 2*x - 5;
a = input('enter a: ');
b = input('enter b: ');
x = 0;
for i = 1:1:100
x =((a*f(b)-b*f(a))/(f(b)-f(a)));
%x = a - (f(a)*(b - a))/((f(b) - f(a)));
if f(x) > 0.00001
b = x;
else
a = x;
end
if abs(f(x)) <= 0.00001
break;
end
end
fprintf('ans = %f\niteration is %d\n', x, i);
TRAPEZOIDAL
f=@(x) 1/(1+x)
n=4
a=0
b=1
h=(b-a)/n
s=0
for i=1:n-1
x=a+i*h
s=s+f(x)
end
t=(h/2.0)*(f(a)+2.0*s+f(b))
t
SIMPSON 1/3
f=@(x) 1/(1+x.^2)
h=0.5
a=0
b=1
n=(b-a)/h
s1=0
for i=1:2:n-1
x1=a+i*h
s1=s1+f(x1)
end
s2=0
for i=2:2:n-1
x2=a+i*h
s2=s2+f(x2)
end
t=(h/3.0)*(f(a)+4.0*s1+2.0*s2+f(b))
t
SIMPSON3/8
f=@(x) 1/(1+x)
h=0.125
a=0
b=1
n=(b-a)/h
s1=0
for i=1:3:n-1
x1=a+i*h
s1=s1+f(x1)
end
s2=0
for i=2:3:n-1
x2=a+i*h
s2=s2+f(x2)
end
s3=0
for i=3:3:n-1
x2=a+i*h
s3=s3+f(x2)
end
t=((3.0*h)/8.0)*(f(a)+3.0*s1+3.0*s2+2.0*s3+
f(b))
t
WEDDLE’S
f=@(x) (cos(x)-log(x)+exp(x)); %exp(sin(x)); %log(x)
;
m=fix(n/6 + 1e-14);
x0=low;
sum=0;
for i=1:m
f1=f(x0);
f2=f(x0+h);
f3=f(x0+2*h);
f4=f(x0+3*h);
f5=f(x0+4*h);
f6=f(x0+5*h);
f7=f(x0+6*h);
sum = sum + ( f1 + 5*f2 + f3 + 6*f4 + f5 + 5*f6 + f7
);
x0=x0+6*h;
%x0
end
plot(xAxisValues,exactResultByDefault(xAxisValues),'bo-
');
hold on;
plot(xAxisValues,yAxisValue,'r.-');
f=@(x, y) (-y);
disp('Enter the intial condition (x0, y0):')
x0=input('Enter x0: ');
y0=input('Enter y0: ');
n=fix(abs(xp-x0)/h + 1e-14);
for i=1:n
y1 = y0 + h*f(x0,y0);
x1=x0+h;
x0=x1;
y0=y1;
end
clear all
close all
RK2
n=fix(abs(xp-x0)/h + 1e-14);
for i=1:n
k1=h*f(x0 , y0);
k2=h*f(x0+h , y0+k1);
x1=x0+h;
x0=x1;
y0=y1;
end
n=fix(abs(xp-x0)/h + 1e-14);
for i=1:n
k1=h*f(x0 , y0);
k2=h*f(x0+h/2 , y0+k1/2);
k3=h*f(x0+h/2 , y0+k2/2);
k4=h*f(x0+h , y0+k3);
x1=x0+h;
x0=x1;
y0=y1;
end