Programming Portion 1 Create a MATLAB function nrootxn that
Solution
Programming Portion Ans
1) The nroot() function
function [y ] = nroot( x,n )
% Function to compute n th root of x
% Using Babylonian Algorithm
y = 1;
for i=1:100
y = y -y/n+x/(n*pow(y,n-1));
end
end
The pow() function
function [ y ] = pow( x,n)
% Function to compute y =x^n
y = 1;
for i=1:n
y = y*x;
end
end
2) The PI() function
function [s] = PI( )
% Function to find the value of pi using infinite product
s= 1;a=1/2;
for i =1:100
rt = nroot(a,2);
s = s*rt;
a = 1/2+(1/2)*rt;
end
s = 2/s;
end
TESTING FUNCTIONS
>> fprintf(\'Actual value=%0.16f PI() function value%0.16f\',pi,PI());
Actual value=3.1415926535897931 PI() function value3.1415926535897931
Diary File exercies
1) The modified nroot() function with tolerence 10^-15
function [y ] = nroot( x,n )
% Function to compute n th root of x
% Using Babylonian Algorithm
y = 1; yp = -1;
while abs(y-yp)>10^-15
yp =y;
y = y -y/n+x/(n*pow(y,n-1));
end
end
Testing of nroot() and nthroot() functions
T = zeros(100,2);
for i =1:100
tic;
c = nroot(2,2);
T(i,1) = toc;
tic;
c = nthroot(2,2);
T(i,2) = toc;
end
Avg = sum(T)/100;
fprintf(\'Average time for nroot =%f\ \',Avg(1));
fprintf(\'Average time for nthroot =%f\ \', Avg(2));
OUTPUT
Average time for nroot =0.000010
Average time for nthroot =0.000089
2)
function [y ] = nroot( x,n )
% Function to compute n th root of x
% Using Babylonian Algorithm
y = 10^100; yp = -1; ct =0;
while abs(y-yp)>10^-16
yp =y;
y = y -y/n+x/(n*pow(y,n-1));
ct =ct+1;
end
fprintf(\'The Function took %d iterations\',ct);
end
OUTPUT
>> nroot(2,2)
The Function took 337 iterations
ans =
1.4142

