Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
53 views

1.0 Bisection Method

The document provides examples of numerical methods for solving equations including: 1) Bisection method - Provides 3 examples of using bisection method to find roots of equations. 2) Newton Raphson method - Provides 4 examples of using Newton Raphson method to approximate roots of equations. 3) Gauss elimination method - Provides 5 examples of using Gauss elimination to solve systems of linear equations. 4) Gauss Jordan method - Provides 1 example of using Gauss Jordan elimination to solve a system of linear equations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

1.0 Bisection Method

The document provides examples of numerical methods for solving equations including: 1) Bisection method - Provides 3 examples of using bisection method to find roots of equations. 2) Newton Raphson method - Provides 4 examples of using Newton Raphson method to approximate roots of equations. 3) Gauss elimination method - Provides 5 examples of using Gauss elimination to solve systems of linear equations. 4) Gauss Jordan method - Provides 1 example of using Gauss Jordan elimination to solve a system of linear equations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 95

1.

0 BISECTION METHOD
2.0 NEWTON RAPHSON
1.0 GAUSS ELIMINATION
2.0 GAUS JORDAN
3.0 LU COMPOSITION
1.0 CURVE FITTING
2.0 LINEARIZATION
3.0 MAXIMUM
4.0 MINIMUM
1.0 EULER
2.0 RK 2
3.0 RK 4
1.0 TRAPEZOIDAL RULE SINGLE
2.0 TRAPEZOIDAL RULE MULTIPLE
3.0 SIMPSON 1/3 SINGLE
4.0 SIMPSON 1/3 MULTIPLE
5.0 SIMPSON 3/8 SINGLE
6.0 SIMPSON 3/8 MULTIPLE
BISECTION METHOD
EXAMPLE 1

% Name : Nurul Syahirah Binti Zulkifli Nor

% Group : PEC2216A2

% ID No. : 2019564227

% This code is to find the void fraction of bed using Bisection Method.

clear all

clc

% Define The Ergun equation

y = @(x)(10*(x^3))-(0.15*(x^2))+(2.05*x)-1.9;

% Define the lower limit (xl) and upper limit (xu)

xl = -2;

xu = 2;

% Define approximate relative error, ea

% Define specified relative error, es

ea = 100; %Dummy value

es = 0.1;

% Check multiplication sign yxl and yxu

sign1 = y(xl)*y(xu);
if sign1 < 0

disp(' ')

disp(' There is root within this bracket ')

else

disp(' ')

disp(' There is no root within this bracket ')

exit

end

disp(' ')

disp('iter xl xu xm ea ')

disp('_________________________________________________ ')

disp(' ')

iter = 0;

xm = 0.5*(xl + xu);

while ea > es

iter = iter+1;

sign2 = y(xl)*y(xm);

if sign2 < 0

xmold = xm;
xu = xm;

xl = xl;

xmnew = 0.5*(xl + xu);

if iter == 1

ea = ea;

else

ea = abs((xmnew-xmold)/xmold)*100;

end

% Display ( iter xl xu xm ea )

elseif sign2 > 0

xmold = xm;

xl = xm;

xu = xu;

xmnew = 0.5*(xl + xu);

if iter == 1

ea = ea;

else

ea = abs((xmnew-xmold)/xmold)*100;

end

end
xm = xmnew;

% Display ( iter xl xu xm ea )

fprintf(' %i %3f %3f %3f %3f \n', iter, xl, xu,xm, ea)

endwhile

disp(' ')

% Display ('The root is =')

% Display (xm)

fprintf('The iteration no is %i and the root is = %5f \n', iter, xm)

EXAMPLE 2

%%bisection method - sir shahrul example

clc

clear all

format short g

xl = 0;

xu = 0.11;

f = @(x) (x^3) - 0.165*(x^2)+ 0.0003994;

fxl = f(xl);

fxu = f(xu);

signcheck = fxl * fxu;

if signcheck < 0;
disp('theres only one root')

xm = (xu+xl)/2;

else signcheck> 0;

disp('theres no root')

end

i=0;

disp ('[i xu xl xm f(xm) epsilonA]');

while(i<4)

xmold=xm;

xm = (xu+xl)/2;

signcheck2 = f(xm) * f(xu);

if signcheck2 < 0;

xl = xm;

else signcheck2 > 0;

xu = xm;

end

xmnew = (xl+xu) /2;

epsilonA = abs((xmnew-xmold)/xmnew)*100;

i= i+1;

display ([i xu xl xm f(xm) epsilonA]);

end
EXAMPLE 3

%code for bisection method

clear all

clc

f=@(x)120*x-(5/6)*x^3-220;

ea=100;

es=0.01;

xL=0;

xU=2;

%xL= input ('input the lower limit');

%xU= input ( 'input the upper limit');

sign1=f(xL)*f(xU);

if sign1<0

disp('')

disp('There is root within this bracket')

else

disp('')

disp('there is no root within this bracket')


exit

end

disp ('')

disp('iter xL xU xm ea')

disp('---------------------------------------------')

disp('')

iter = 0;

xm=0.5*(xL+xU);

while ea > es

iter = iter + 1;

sign2 = f(xL)*f(xm);

if sign2 < 0

xmold = xm;

xU=xm;

xL=xL;
xmnew = 0.5*(xL+xU);

if iter==1

ea=ea;

else

ea = abs((xmnew-xmold)/xmold)*100;

end

% disp([iter xL xU xm ea])

elseif sign2>0

xmold =xm;

xL=xm;

xU= xU;

xmnew = 0.5*(xL+xU);

if iter ==1

ea = ea;

else

ea = abs ((xmnew-xmold)/xmold)*100;

end
%disp {(iter xL xU xm ea)}

end

xm = xmnew;

%disp {(iter xL xU xm ea)}

fprintf('%i %3f %3f %3f %3f \n', iter, xL, xU, xm, ea)

end

disp('')

%disp('The root is =')

%disp (xm)

fprintf('the iteration no is %i and the root is =%5f \n', iter, xm)


NEWTON RAPHSON METHOD
EXAMPLE 1

% Name : Nurul Syahirah Binti Zulkifli Nor

% Group : PEC2216A2

% ID No. : 2019564227

% This code is to find the void fraction of bed using Newton Raphson Method.

clear all

clc

% Define the initial guess of root, x0

x0 = 1;

% Define absolute relative error, ea

% Define specified relative error, es

ea = 100; %Dummy value

es = 0.1;

x = x0;

% Define The Ergun equation

y = @(x)(10*(x^3))-(0.15.*(x^2))+(2.05*x)-1.9;

% Define the differentiation of The Ergun equation


dy = @(x)(30*(x^2))-(3*x)+2.05;

iter = 0;

disp('iter x ea ')

disp('_________________________ ')

disp('')

while ea > es

iter = iter+1;

xold = x;

x = x-(y(x)/dy(x));

xnew = x;

if iter == 1

ea = ea;

else

ea = abs((xnew-xold)/xnew)*100;

endif

fprintf(' %i %3f %3f \n', iter, x, ea)

endwhile

disp(' ')
fprintf('The root of this equation is %5f by iteration of %i with error of %3f
\n',x,iter,ea)

EXAMPLE 2

x = 4.2;

epsilonS = 0.0001;

epsilonA = 100;

i=0;

disp('i x x0 epsilonA');

while epsilonA > epsilonS

x0=x;

i=i+1;

f = (-2)+(6*x)-(4*(x^2))+(0.5*(x^3));

df= 6-(8*x)+(1.5*(x^2));

x = (x0)-(f/df);

epsilonA = abs ((x-x0)/x)*100;

disp([i x x0 epsilonA]);

end

EXAMPLE 3

%% newton- sir shahrul

format short g

clear all

clc

x = 0.05;
disp('i x x0 epsilonA');

i=0;

while(i<4)

x0=x;

i = i+1;

f = (x^3) - 0.165*(x^2)+ 0.0003994;

df =3*(x^2)-(0.33*x);

x = x0 - (f/df);

epsilonA = abs ((x-x0)/x)*100;

display([i x x0 epsilonA])

end

EXAMPLE 4

%code for newton-raphson method

clear all

clc

x0=3;

es=1;

ea=100;

x=x0;

df = @(x) 120 -15/6*x^2;


f = @(x)120*x-(5/6)*x^3-220;

iter=0;

disp ('iter x df')

disp ('-------------------------')

disp ('')

while ea > es

iter = iter + 1;

xold = x;

x=x-(f(x)/df(x));

xnew=x;

if iter ==1

ea=ea;

else

ea =abs ((xnew-xold)/xnew)*100;

endif

fprintf ('%i %3f %3f \n', iter, x, ea)


end

disp ('')

fprintf ('the root of this equation is %5f by iteration of %i with error of %3f\n',x,iter,ea)
GAUS ELIMINATION METHOD
EXAMPLE 1

%Gauss Elimination - husna

format short g

%Left side of the matrix

A = [ 1 7 -4 ; 4 -4 9 ; 12 -1 3]

pause;

%Right side of the matrix

B = [-51 ; 62 ; 8]

pause;

%Create Augemented Matrix

C = [A B]

pause;

%Zero at entry first column

C(2,:) = C(2,:) - C(1,:) / C(1,1)* C(2,1)

pause;

C(3,:) = C(3,:) - C(1,:) / C(1,1)* C(3,1)

pause;

%Zero at second Column

C(3,:) = C(3,:) - C(2,:) / C(2,2)* C(3,2)


pause;

%Backward subtitution

c = C(3,4)/C(3,3)

pause;

b =(C(2,4) - C(2,3) * c)/ C(2,2)

pause;

a =(C(1,4) - (C(1,3) * c) - (C(1,2) * b)) / C(1,1)

answer = [a;b;c]

EXAMPLE 2

clear all

clc

format short g

%% left side

A = [25 5 1;64 8 1;144 12 1]

%% right side

B = [106.8;177.2;279.2]

%% augemented form

C = [A B]

%% zero at the first column

C(2,:) = C(2,:) - (C(2,1)/C(1,1)) * C(1,:)

C(3,:) = C(3,:) - (C(3,1)/C(1,1)) * C(1,:)

%% zero at the second column


C(3,:) = C(3,:) - (C(3,2)/C(2,2)) * C(2,:)

%% Backward elimination

c = C(3,4)/C(3,3)

b = (C(2,4)-C(2,3)*c)/C(2,2)

a = (C(1,4) - (C(1,3)*c) - (C(1,2)*b))/C(1,1)

solution = [a;b;c]

EXAMPLE 3

% Gauss Elimination

clear all

clc

A = [ 1 1 -1 ; 1 -2 3 ; 2 3 1 ];

B = [ 4; -6; 7];

AB = [ A B ]

AB (2, :) = AB (2,:)-AB(1, :)

AB (3, :) = AB (3, :)-2*AB(1,:)

AB (3, :) = AB (3, :)-(1/-3)*AB(2, :)

disp ('The value of the uknown (x1; x2; x3) is');

x2=A\B
EXAMPLE 4

clc; clear;

A = [1 -3 1;

2 -8 8;

-6 3 -15];

b = [4; -2; 9];

% Perform matrix augumentation

Ab = [ A b]

% Perform forward elimination on First columns

alpha = -Ab(2,1)/Ab(1,1)

Ab(2,:)= Ab(2,:)+alpha*Ab(1,:)

alpha = -Ab(3,1)/Ab(1,1)

Ab(3,:)= Ab(3,:)+alpha*Ab(1,:)

% Perform forward elimination on Second columns

alpha = -Ab(3,2)/Ab(2,2)

Ab(3,:)= Ab(3,:)+alpha*Ab(2,:)
% Perform Back substituion to compute unknown

% Exact solution

solution=A\b

EXAMPLE 5

clc; clear; close;

A = [1 -3 1;

2 -8 8;

-6 3 -15];

b = [4; -2; 9];

% Augmenting matrix A and b to Ab

Ab = [ A b];

[m,n] = size(Ab);

disp('The original augmented matrix is=')

disp('---------------------------------')

disp(Ab)

disp(' ')

% Performing pivoting

for j =1:m-1

for z =2:m
if Ab(j,j) == 0

t = Ab(j,:);

Ab(j,:) = Ab(z,:);

Ab(z,:) = t;

end

end

% Convert the element below the pivot to zero

for i = j+1:m

disp(['Performing Forward Elimination at column ',num2str(j), ' and row ',


num2str(i)])

disp('------------------------------------------------------')

disp(' ')

disp('*************************')

disp('Before Forward Elimination')

disp('*************************')

disp( Ab(i,:))

Ab(i,:) = Ab(i,:) - Ab(j,:)*(Ab(i,j)/Ab(j,j));

disp('*************************')

disp('After Forward Elimination')

disp('*************************')

disp( Ab(i,:))

disp(' ')

end
end

disp(' Final Ab before back substituion')

disp(Ab)

% Initialize x vectors

x = zeros(1,m);

% Back substitution to obtain the unknown

disp(' ')

disp('Performing Back Substitution to obtain unknowns')

disp('-----------------------------------------------')

for s =m:-1:1

c = 0;

for k =2:m

c = c + Ab(s,k)*x(k);

end

x(s) = (Ab(s,n) - c)/Ab(s,s);

disp(['x(',num2str(s),')=',num2str(x(s))])

end

% disp('Gauss Elimination Method Solution')

% Ab

% x'
disp(' ')

disp('Compare with symbolic solution')

disp('------------------------------')

x2 = A\b
GAUSS JORDAN METHOD
EXAMPLE 1

%Gauss Jordan Elimination - husna

format short g

%Left side of the matrix

A = [ 1 7 -4 ; 4 -4 9 ; 12 -1 3]

pause

%Right side of the matrix

B = [-51 ; 62 ; 8]

pause

%Create Augemented Matrix

C = [A B]

pause

%Zero at entry first column

C(2,:) = C(2,:) - C(1,:) / C(1,1)* C(2,1)

pause

C(3,:) = C(3,:) - C(1,:) / C(1,1)* C(3,1)

pause

%Zero at second Column

C(3,:) = C(3,:) - C(2,:) / C(2,2)* C(3,2)


pause

%make C(2,2) = 1

C(2,:) = C(2,:)/C(2,2)

pause

%make C(3,3) = 1

C(3,:) = C(3,:)/C(3,3)

pause

%zero column 3

C(2,:) = C(2,:)- C(3,:) / C(3,3)* C(2,3)

pause

C(1,:) = C(1,:)- C(3,:) / C(3,3)* C(1,3)

pause

%zero column 2

C(1,:) = C(1,:)- C(2,:) / C(2,2)* C(1,2)

disp('calculation completee yeay')


EXAMPLE 2

clear all

clc

format short g

%% left side

A = [25 5 1;64 8 1;144 12 1]

%% right side

B = [106.8;177.2;279.2]

%% augemented form

C = [A B]

%% one at the C(1,1)

C(1,:) = C(1,:)/C(1,1)

%% zero at the first column

C(2,:) = C(2,:) - (C(2,1)/C(1,1)) * C(1,:)

C(3,:) = C(3,:) - (C(3,1)/C(1,1)) * C(1,:)

%% zero at the second column

C(3,:) = C(3,:) - (C(3,2)/C(2,2)) * C(2,:)

%% one at C(2,2) and C(3,3)

C(2,:) = C(2,:)/C(2,2)
C(3,:) = C(3,:)/C(3,3)

pause

%% zero at the third column

C(2,:) = C(2,:) - (C(2,3)/C(3,3)) * C(3,:)

C(1,:) = C(1,:) - (C(1,3)/C(3,3)) * C(3,:)

%% zero at the second column

C(1,:) = C(1,:) - (C(1,2)/C(2,2)) * C(2,:)

EXAMPLE 3

clc; clear; close;

A = [1 -3 1;

2 -8 8;

-6 3 -15];

b = [4; -2; 9];

% Augmenting matrix A and b to Ab

Ab = [ A b];

[m,n] = size(Ab);

% Performing pivoting

for j =1:m-1
for z =2:m

if Ab(j,j) == 0

t = Ab(1,:); %

Ab(1,:) = Ab(z,:); %

Ab(z,:) = t;

end

end

% Convert the element below the pivot to zero

for i = j+1:m

Ab(i,:) = Ab(i,:) - Ab(j,:)*(Ab(i,j)/Ab(j,j));

Ab

end

end

for j = m:-1:2

for i = j-1:-1:1

Ab(i,:) = Ab(i,:) - Ab(j,:)*(Ab(i,j)/Ab(j,j));

end

end

% Back substitution to obtain the unknown

for s =1:m

Ab(s,:) = Ab(s,:)/Ab(s,s);

x(s) = Ab(s,n);
end

disp('Gauss Jordan Method')

Ab

x'

disp(' ')

disp(' Compare with symbolic solution')

x2 = A\b

disp(' ')

disp(' Using row -reduced echelon command')

solution =rref(Ab)
LU DECOMPOSITION METHOD
EXAMPLE 1

%LU decomposition - husna

format short g

%Left side of the matrix

disp(' this is a left side of the matrix')

A = [ 1 7 -4 ; 4 -4 9 ; 12 -1 3]

U = [A]

pause

clc

%Zero at entry first column

U(2,:) = U(2,:) - U(1,:) / U(1,1)* U(2,1)

pause

U(3,:) = U(3,:) - U(1,:) / U(1,1)* U(3,1)

pause

% Calculate L32

disp('to find L32')

L32 = U(3,2) / U(2,2)

pause
%Zero at second Column

U(3,:) = U(3,:) - U(2,:) / U(2,2)* U(3,2)

%the l values

disp('to find L21 and L31')

[A]

L21 = A(2,1)/A(1,1)

L31 = A(3,1)/A(1,1)

%Create the lower part and upper part

L = [ 1 0 0 ; L21 1 0 ; L31 L32 1 ]

U = [ U(1,:) ; U(2,:) ; U(3,:)]

%check to comfirm same with [A]

LU = [L*U]

[A]

%first solve [L][Z]=[C]

%by solving the z unknown.

pause

clc

disp('lets solve the [Z]')

disp('[L][Z]=[C]')

[L]
%right side of the matrix

C = [-51 ; 62 ; 8]

LC = [L C]

B = [A C]

%Do forward elimination

z1 = C(1,1)

z2 = C(2,1) - (L(2,1)*z1)

z3 = C(3,1) - (L(3,1)*z1) - (L(3,2)*z2)

%Then solve [U][X]=[Z]

pause

clc

disp('lets solve the [X]')

disp('[U][X]=[Z]')

[U]

Z = [z1 ; z2 ; z3]

ZU = [Z U]

x3= Z(3,1) / U(3,3)

x2=(Z(2,1) - U(2,3)*x3) / U(2,2)

x1=(Z(1,1) - (U(1,3)*x3) - (U(1,2)*x2)) / U(1,1)

X=[x1 ; x2 ; x3]
EXAMPLE 2

clear all

clc

format short g

%% left side

A = [25 5 1;64 8 1;144 12 1]

U = [A]

%% zero at the first column

U(2,:) = U(2,:) - (U(2,1)/U(1,1))* U(1,:)

U(3,:) = U(3,:) - (U(3,1)/U(1,1))* U(1,:)

%% to find l32 use the last matrix

l32 = U(3,2)/U(2,2)

%% zero at the second column

U(3,:) = U(3,:) - (U(3,2)/U(2,2))* U(2,:)

%% to find l21 and l31 using matrix A

l21 = A(2,1)/A(1,1)

l31 = A(3,1)/A(1,1)

%% display matrix L and U

L = [1 0 0;l21 1 0;l31 l32 1]

U = [U(1,:);U(2,:);U(3,:)]
%% LU must be same with A

LU = [L*U]

if LU == A

disp ('same!! Proceed')

else

disp('not same! WRONG')

end

%% right side

C = [106.8;177.2;279.2]

%% to find Z

%%[L][Z] = [C]

LC = [L C]

Z1 = LC(1,4)

Z2 = LC(2,4) - (LC(2,1)*Z1)

Z3 = LC(3,4) - (LC(3,1)*Z1) - (LC(3,2)*Z2)

Z = [Z1;Z2;Z3]

%% to find X

%%[U][X] = [Z]

UZ = [U Z]
X3 = UZ(3,4)/UZ(3,3)

X2 = (UZ(2,4)- UZ(2,3)*X3)/UZ(2,2)

X1 = (UZ(1,4)- UZ(1,3)*X3 - UZ(1,2)*X2)/UZ(1,1)

X = [X1;X2;X3]

EXAMPLE 3

% LU Decomposition

clear all

clc

A = [ 1 1 -1; 1 -2 3; 2 3 1];

B = [ 4; -6; 7];

AB = [ A B]

[L, U, P] = lu (A)

disp ('The solution using LU Decomposition is')

disp ('--------------------------------------------')

y = L\(P*B);

x = U\y;

disp (' ')


disp ('Compare with symbolic equation')

disp ('----------------------------------------------')

x2 = A\B

Gauss jordan

clc; clear; close;

A = [1 -3 1;

2 -8 8;

-6 3 -15];

b = [4; -2; 9];

% Augmenting matrix A and b to Ab

Ab = [ A b];

[m,n] = size(Ab);

% Performing pivoting

for j =1:m-1

for z =2:m

if Ab(j,j) == 0
t = Ab(1,:); %

Ab(1,:) = Ab(z,:); %

Ab(z,:) = t;

end

end

% Convert the element below the pivot to zero

for i = j+1:m

Ab(i,:) = Ab(i,:) - Ab(j,:)*(Ab(i,j)/Ab(j,j));

Ab

end

end

for j = m:-1:2

for i = j-1:-1:1

Ab(i,:) = Ab(i,:) - Ab(j,:)*(Ab(i,j)/Ab(j,j));

end

end

% Back substitution to obtain the unknown

for s =1:m

Ab(s,:) = Ab(s,:)/Ab(s,s);

x(s) = Ab(s,n);

end
disp('Gauss Jordan Method')

Ab

x'

disp(' ')

disp(' Compare with symbolic solution')

x2 = A\b

disp(' ')

disp(' Using row -reduced echelon command')

solution =rref(Ab)

EXAMPLE 4

clc; clear; close;

A = [1 -3 1;

2 -8 8;

-6 3 -15];

b = [4; -2; 9];

[ L, U ,P] = lu(A)

disp('The solution using LU Decomposition is')


disp('--------------------------------------')

y = L\(P*b);

x = U\y

disp(' ')

disp('Compare with symbolic solution')

disp('------------------------------')

x2 = A\b
CURVE FITTING
EXAMPLE 1

% Name : Nurul Syahirah Binti Zulkifli Nor

% Group : PEC2216A2

% ID NO. : 2019564227

% This code is to find the equation of the line that best fits the data and the r square
value

% Using curve fitting ( Linear Regression and Polynomial Regression )

clear all

clc

% The following data shows the relationship between the viscosity of SAE 70 oil and
temperature

Temperature = [ 26.67 93.33 148.89 315.56 ];

Viscosity = [ 1.35 0.085 0.012 0.00075 ];

% After taking log of the data, define the temperature log(x) and the viscosity of SAE
70 oil log(y)

x = [ 1.426023016 1.970021266 2.17286553 2.499081947 ];

y = [ 0.130333768 -1.070581074 -1.920818754 -3.124938737 ];

% Plot the graph to show the relationship between x and y

figure(1)

plot(x,y,'r--')
xlabel('Temperature (^oC)')

ylabel('Viscosity (N.s/m^2)')

title('The Temperature of The Viscosity of SAE 70 oil')

grid on

% Perform curve fitting on x and y data

% Start with linear regression (y = a1*x + a0)

% Use 1st Order (order = 1)

disp('============================================')

disp(' LINEAR REGRESSION ')

disp(' (1st Order) ')

disp('============================================')

disp('')

order = 1;

coefficient_linear= polyfit(x,y,order);

disp('Coefficient of Linear Regression (1st Order)')

disp('')

disp(' a0 a1 ')

disp(coefficient_linear)

disp('')

y = [ 0.130333768 -1.070581074 -1.920818754 -3.124938737 ];

Viscosity_Prediction_linear = polyval(coefficient_linear,x)

% Compare the actual viscosity and the predicted viscosity


compare_linear = [y' Viscosity_Prediction_linear'];

disp('')

disp('The comparison between the actual viscosity and predicted viscosity')

disp('')

disp(' Actual Predicted')

disp(' Viscosity Viscosity')

disp(' (y)')

disp('')

disp(compare_linear)

disp('')

% Compute r square

St_linear = sum((y - mean(y)).^2);

Sr_linear = sum((y - Viscosity_Prediction_linear).^2);

r_square_linear = (St_linear - Sr_linear)/(St_linear);

fprintf('The r square of linear regression is = %5f \n', r_square_linear)

% Plot the graph (actual data + linear prediction)

figure(2)

plot(x,y,'r',x,Viscosity_Prediction_linear,'b--')

legend('Actual Data','Linear Regression')

xlabel('Temperature (^oC)')

ylabel('Viscosity (N.s/m^2)')

title('The Temperature of The Viscosity of SAE 70 oil')


grid on

%
=================================================================
=============

% Improve the model by using polynomial regression (y = a2*x^2 + a1*x + a0)

% Use 2nd Order (order = 2)

disp('')

disp('============================================')

disp(' POLYNOMIAL REGRESSION ')

disp(' (2nd Order) ')

disp('============================================')

disp('')

order = 2;

coefficient_polynomial2= polyfit(x,y,order);

disp('Coefficient of Polynomial Regression (2nd Order)')

disp('')

disp(' a0 a1 a2')

disp(coefficient_polynomial2)

disp('')

y = [ 0.130333768 -1.070581074 -1.920818754 -3.124938737 ];

Viscosity_Prediction_polynomial2 = polyval(coefficient_polynomial2,x)

% Compare the actual viscosity and the predicted viscosity

disp('')
disp('The comparison between the actual viscosity and predicted viscosity')

disp('')

disp(' Actual Predicted')

disp(' Viscosity Viscosity')

disp(' (y)')

disp('')

compare_polynomial2 = [y' Viscosity_Prediction_polynomial2'];

disp(compare_polynomial2)

disp('')

% Compute r square

St_polynomial2 = sum((y - mean(y)).^2);

Sr_polynomial2 = sum((y - Viscosity_Prediction_polynomial2).^2);

r_square_polynomial2 = (St_polynomial2 - Sr_polynomial2)/(St_polynomial2);

fprintf('The r square of polynomial regression (2nd Order) is = %5f \n',


r_square_polynomial2)

%
=================================================================
=============

% Improve the model by using polynomial regression (y = a3*x^3 + a2*x^2 + a1*x +


a0)

% Use 2nd Order (order = 3)

disp('')
disp('============================================')

disp(' POLYNOMIAL REGRESSION ')

disp(' (3rd Order) ')

disp('============================================')

disp('')

order = 3;

coefficient_polynomial3= polyfit(x,y,order);

disp('Coefficient of Polynomial Regression (3rd Order)')

disp('')

disp(' a0 a1 a2 a3')

disp(coefficient_polynomial3)

disp('')

y = [ 0.130333768 -1.070581074 -1.920818754 -3.124938737 ];

Viscosity_Prediction_polynomial3 = polyval(coefficient_polynomial3,x)

% Compare the actual viscosity and the predicted viscosity

disp('')

disp('The comparison between the actual viscosity and predicted viscosity')

disp('')

disp(' Actual Predicted')

disp(' Viscosity Viscosity')

disp(' (y)')

disp('')

compare_polynomial3 = [y' Viscosity_Prediction_polynomial3'];

disp(compare_polynomial3)
disp('')

% Compute r square

St_polynomial3 = sum((y - mean(y)).^2);

Sr_polynomial3 = sum((y - Viscosity_Prediction_polynomial3).^2);

r_square_polynomial3 = (St_polynomial3 - Sr_polynomial3)/(St_polynomial3);

fprintf('The r square of polynomial regression (3rd 0rder) is = %5f \n',


r_square_polynomial3)

% Plot the graph (actual data + linear prediction + polynomial prediction2 +


polynomial prediction3)

figure(3)

plot(x,y,'r',x,Viscosity_Prediction_linear,'k--',x,Viscosity_Prediction_polynomial2,'g',
x,Viscosity_Prediction_polynomial3,'bo')

legend('Actual Data','Linear Regression','Polynomial(2nd Order)','Polynomial(3rd


Order)')

xlabel('Temperature (^oC)')

ylabel('Viscosity (N.s/m^2)')

title('The Temperature of The Viscosity of SAE 70 oil')

grid on
EXAMPLE 2

%code for curve fitting using octave

clc;clear;close;

%assign the independent var (t) and the dependent variable (v) to matrix

t= [1:1:15];

v=[10 16.3 23 27.5 31 35.6 39 41.5 42.9 45 46 45.5 46 49 50];

%plot the measured data

figure (1)

plot(t,v,'ro-')

xlabel ('Time (seconds)')

ylabel ('Velocity (m/s)')

title ('velocity vs time')

grid on

%fit the measured data with OCTAVE built-in command (polyfit,polyval)

order =3;

coef = polyfit(t,v, order ) % linear curve fitting (v = alt + a0)


predicted_v = polyval (coef,t) %predict the velocity

%to compare the measured velocity and predicted velocity

disp ([v' predicted_v'])

%plot the measured data (v) and the predicted data (predicted v)

figure (2)

plot (t,v,'r*') %plot the measured data (v)

hold on

plot (t, predicted_v, 'go') %plot the predicted data

xlabel ('Time (seconds)')

ylabel ('Velocity (m/s)')

title ('the measured data and the predicted data velocity')

legend ( 'the measured velocity', 'the predicted velocity')

grid on

disp ('')

%compute r square value

st = sum ((v-mean (v)).^2);

sr = sum ((v-predicted_v).^2);

r_square = (st-sr)/st
disp ('')

predictedv = polyval (coef,6.3)

%non linear regression for exponential law

clc; clear; close;

%insert x and y value to OCTAVE

T= [0 5 10 20 30 40];

n= [ 1.787 1.519 1.307 1.002 0.7975 0.6529];

%plot the graph

figure (1)

plot (T,n,'r*-')

xlabel ('Temperature(T)')

ylabel ('Viscosity(n)')

title ('Viscosity vs Temperature')

grid on

%Transform the data so that this relationship can be linearized

xln=T;

yln=log(n);

%perform curve fitting base on linear retaionship (order=1)


order=1;

coef= polyfit(xln,yln,order)

predicted_yln= polyval(coef,xln)

disp(' T ln n');

disp([T' predicted_yln'])

disp(' ');

figure(2)

hold on

plot (xln,yln,'g*-')

xlabel ('Temperatur(T)')

ylabel ('Viscosity(ln n)')

title ('Viscosity vs Temperature')

grid on

predictednifT = polyval(coef,15.8)

disp(' ');

beta1_valueB= coef(1)

alpha1_valueD= exp(coef(2))

disp(' ');

%compute r square value

St= sum((yln -mean(yln)).^2);


Sr=sum((yln -predicted_yln).^2);

r_square= (St-Sr)/St

EXAMPLE 4

%Curve fitting

clc ;

clear all;

%Store the independent variables values (x) and the dependent in OCTAVE

x=[1:1:5];

y=[0.5,2,2.9,3.5,4];

%Plot the measured data

figure(1)

plot(x,y,'bo-')

xlabel('x')

ylabel('y')

title('y vs x')

lnx=log(x)%linearization

figure(2)

plot(lnx,y)

xlabel('lnx')

ylabel ('y')
title('y vs lnx')

%Perform curve fitting

order=1; %linear curve fitting

coef= polyfit(lnx,y,order)

y_predicted= polyval(coef,lnx)

%Plot the measured dependent variable data (y) and the predicted y

figure(3)

plot(lnx,y,'r*-',lnx,y_predicted,'go-')

xlabel('lnx')

ylabel ('y')

title('y vs lnx')

%Perform r square

St=sum((y-mean(y)).^2);

Sr=sum((y-y_predicted).^2);

r_square=(St-Sr)/St

%Prediction what is the value of y if x=3.3

answer=polyval(coef,log(3.3))
EXAMPLE 5

clear;

clc;

k=[1.1 2.4 5.3 7.6 8.9];

c=[0.5 0.8 1.5 2.5 4];

figure(1);

plot(c,k,'go-');

xlabel('c value (mg/L)');

ylabel('k value (per day)');

title('c vs k') ;

grid on;

coef=polyfit(c, k,1)

predicted_k=polyval(coef, c)

disp([k' predicted_k'])

figure(2);

plot(c, k, 'go-') ;

hold on;

plot(c, predicted_k, 'r*-') ;

xlabel('c value (mg/L)') ;

ylabel('k value and predicted k value (per day)') ;

title('linearization relationship, c vs k') ;


grid on;

kmax=1/coef(2)

cs=kmax*coef(1)

st=sum((k-mean(k)).^2);

sr=sum((k-predicted_k).^2);

rsq=(st-sr)/st

predict_k=polyval(coef, 2.8)

k=[1.1 2.4 5.3 7.6 8.9];

c=[0.5 0.8 1.5 2.5 4];

cnew=1./c

knew=1./k

figure(3)

plot(c,k,'go-');

hold on;

plot(cnew, knew, 'k*-')

xlabel('c (mg/L) and 1/c value ')

ylabel('k (per day) and 1/k value ')

title('transform data of c (mg/L) and k (per day)')

grid on;
coef=polyfit(cnew, knew, 2)

predicted_knew=polyval(coef, cnew)

st=sum((knew-mean(knew)).^2);

sr=sum((knew-predicted_knew).^2);

rsq=(st-sr)/st
EULER’S METHOD
EXAMPLE 1

%this script is to solve ODE using Euler

%The equation to be solve is dy/dt= -2ty, y(0) =1, 0<t<5

clear all

clc

%innitialization of the initial value

t0 = 0;

y0 = 1;

tEnd = 5;

h = 0.01;

N = (tEnd-t0)/h;

EXAMPLE 2

%%Euler

clear all

clc

t0 = 0;

y0 = 2;

tend = 4;

h = 1;
N = (tend -t0)/h;

%% Initialize the solution of the ODE

T = [t0:h:tend]';

Y = zeros(N+1,1);

Y(1) = y0;

%% solve the ODE using Euler algorithm

for i = 1:N

fi = 4*exp(0.8*T(i))-0.5*Y(i);

Y(i+1) = Y(i) + h*fi;

end

%% Compute the exact solution

YTrue = (4/1.3)*(exp(0.8*T)- exp(-0.5*T)) + 2*(exp(-0.5*T));

%% display the numerical values of ODE

disp([YTrue Y])

%% plot the exact and the numerical values solution

plot (T,Y,'m',T,YTrue,'b')

title(strcat('Comparison between the numerical values solution h=',num2str(h),'& exact


solution'))
xlabel('Time')

ylabel('solution of Y')

legend('Numerical solution','Exact solution')

grid on

%% Acess the maximum error

True_error = abs((YTrue-Y));

Max_error = max(True_error)

EXAMPLE 3

%Solve the ode using Euler algorithm

for i = 1:N

fi = -2*T(i)*Y(i);

Y(i+1) = Y(i) + h*fi;

end

%compute the exact solution

YTrue = exp (-T.^2);

%display the numerical value of ode


disp([YTrue Y])

%plot the exact and the numerical value solution

plot(T,Y,'g',T,YTrue,'b')

title (strcat('Comparison between the neumerical values solution h=', num2str(h),' &
exact solution'))

xlabel('Time')

ylabel ('Solution of Y')

legend('Numerical solution','Exact solution')

grid on

%access the maximum error

True_error= abs((YTrue-Y));

Max_error = max (True_error)


HEUNS METHOD
EXAMPLE 1

%%heuns

clear all

clc

t0 = 0;

y0 = 2;

tend = 4;

h = 1;

N = (tend -t0)/h;

%% Initialize the solution of the ODE

T = [t0:h:tend]';

Y = zeros(N+1,1);

Y(1) = y0;

%% solve the ODE using heuns algorithm

for i = 1:N

k1 = ODEfunction(T(i),Y(i));

k2 = ODEfunction(T(i) + h,Y(i)+ h*k1);

Y(i+1) = Y(i) + h/2*(k1+k2);

end
%% Compute the exact solution

YTrue = (4/1.3)*(exp(0.8*T)- exp(-0.5*T)) + 2*(exp(-0.5*T));

%% display the numerical values of ODE

disp([YTrue Y])

%% plot the exact and the numerical values solution

plot (T,Y,'m',T,YTrue,'b')

title(strcat('Comparison between the numerical values solution h=',num2str(h),'& exact


solution'))

xlabel('Time')

ylabel('solution of Y')

legend('Numerical solution','Exact solution')

grid on

%% Acess the maximum error

True_error = abs((YTrue-Y));

Max_error = max(True_error)
EXAMPLE 2

%this script is to solve ODE using heuns method

%The equation to be solve is dy/dt= -2ty, y(0) =1, 0<t<5

clear all; clc; close;

%innitialization of the initial value

t0 = 0;

y0 = 1;

tEnd = 5;

h = 0.5;

N = (tEnd-t0)/h;

%initialize the solution of the ODE

T = (t0:h:tEnd)';

Y = zeros(N+1,1);

Y(1) = y0;

%Solve the ode using Heuns algorithm

for i = 1:N

K1 = myODEfunc(T(i),Y(i));

K2 = myODEfunc(T(i) +h, Y(i)+h*K1);


Y(i+1) = Y(i) + h/2*(K1+K2);

end

%compute the exact solution

YTrue = exp (-T.^2);

%display the numerical value of ode

disp([YTrue Y])

%plot the exact and the numerical value solution

plot(T,Y,'g',T,YTrue,'b')

title (strcat('Comparison between the neumerical values solution h=', num2str(h),' &
exact solution'))

xlabel('Time')

ylabel ('Solution of Y')

legend('Numerical solution','Exact solution')

grid on

%access the maximum error

True_error= abs((YTrue-Y));

Max_error = max (True_error)

function [ u ]= myODEfunc(T,Y)

%untitled summary of this function goes here

%detailed explanation goes here


u= -2*t*y;

End
RUNGEE KUTTA
EXAMPLE 1

%this script is to solve ODE using rk 4th order method

%The equation to be solve is dy/dt= -2ty, y(0) =1, 0<t<5

clear all; clc; close;

%initialization of the initial value

t0 = 0;

y0 = 1;

tEnd = 5;

h = 0.05;

N = (tEnd-t0)/h;

%initialize the solution of the ODE

T = (t0:h:tEnd)';

Y = zeros(N+1,1);

Y(1) = y0;

%Solve the ode using RK 4th order algorithm

for i = 1:N

K1 = myODEfunc(T(i),Y(i));
K2 = myODEfunc(T(i) +h, Y(i)+h*K1);

K3 = myODEfunc (T(i)+h/2,Y(i)+h*K2/2);

K4 = myODEfunc(T(i)+h,Y(i)+h*K3);

Y(i+1) = Y(i) + h/6*(K1+2*K2+2*K3+K4);

end

function [ u ]= myODEfunc(t,y)

%untitled summary of this function goes here

%detailed explaination goes here

u= -2*t*y;

end

%compute the exact solution

YTrue = exp (-T.^2);

%display the numerical value of ode

disp([YTrue Y])

%plot the exact and the numerical value solution

plot(T,Y,'g',T,YTrue,'b')

title (strcat('Comparison between the neumerical values solution h=', num2str(h),' &
exact solution'))

xlabel('Time')

ylabel ('Solution of Y')


legend('Numerical solution','Exact solution')

grid on

%access the maximum error

True_error= abs((YTrue-Y));

Max_error = max (True_error)


Numerical

clc; clear; close;

a= 8;

b= 30;

n= 1;

M = @(x)2000*log(140000./(140000-2100.*x))-9.8.*x;

%Declare the exact value (calculator)

Exact= 11061.34

%----------------------------------------------------

%trapezoidal rule (single)

h=(b-a); %define the interval value

x=a:h:b;

ITrapSingle= h/2*(M(x(1))+ M(x(n+1)))

err = abs ((Exact - ITrapSingle)/Exact)*100

%Display results

disp(' ')

disp([' For h=',num2str (h), ' % True Error =', num2str(err), 'n = ', num2str(n), ' I =',
num2str(ITrapSing), ' Trapezoidal Single'])

disp(' ')

%-------------------------------------------------------
%Trapezoidal Rule (Multiple)

n=40;

h= (b-a)/n;

x= a:h:b;

ITrapeMultiple= h/2*(M(x(1))+2*sum(M(x(2:n)))+M(x(n+1)))

err= abs ((Exact - ITrapeMultiple)/Exact)*100

%Display results

disp(' ')

disp([' for h =', num2str(h), '%True error=', num2str(err),' n=', num2str(n), ' I=',
num2str(ITrapeMultiple)' ' Trapezoidal Multiple'])

disp(' ')

%------------------------------------------------------------

%simpson 1/3 single

n=4;

h=(b-a)/n;

x=a:h:b;

ISimps13Single = h/3*(M(x(1))+4*(M(x(2))+(M(x(n+1)))))

err=abs((Exact-ISimps13Single)/Exact)*100

%Display results

disp(' ')
disp([' for h =', num2str(h), '%True error=', num2str(err),' n=', num2str(n), ' I=',
num2str(ISimps13single)' ' Simpson 1/3 single'])

disp(' ')

%----------------------------------------------------------------

%simpson 1/3 multiple

n=4;

h=(b-a)/n;

x= a:h:b;

ISimps13Multiple = h/3*(M(x(1))+4*sum(M(x(2:2:n)))+2*sum(M(x(3:2:n-
1)))+M(x(n+1)))

err= abs((Exact-ISimps13Multiple)/Exact)*100

%Display results

disp(' ')

disp([' for h =', num2str(h), '%True error=', num2str(err),' n=', num2str(n), ' I=',
num2str(ISimps13Multiple)' ' Simpson 1/3 Multiple'])

disp(' ')

%------------------------------------------------------------------

%Simpson 3/8 single

n=3;

h=(b-a)/n;

x=a:h:b;
ISimps38Single=3*h/8*(M(x(1))+3*M(x(2))+3*M(x(3))+M(x(n+1)))

err=abs((Exact-ISimps38Single)/Exact)*100

%Display results

disp(' ')

disp([' for h =', num2str(h), '%True error=', num2str(err),' n=', num2str(n), ' I=',
num2str(ISimps38Single)' ' Simpson 3/8 Single'])

disp(' ')

%-----------------------------------------------------------------

%simpson3/8(multiple)

n= 9

h=(b-a)/n;

x=a:h:b;

ISamps38Multiple=3*h/8*(M(x(1))+3*sum(M(x(2:3:n-
1)))+3*sum(M(x(3:3:n)))+2*sum(M(x(4:3:n-2)))+M(x(n+1)))

err=abs((Exact-ISamps38Multiple)/Exact)*100

%Display results

disp(' ')

disp([' for h =', num2str(h), '%True error=', num2str(err),' n=', num2str(n), ' I=',
num2str(ISimps38Multiple)' ' Simpson 3/8 Multiple'])

disp(' ')

You might also like