Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I would like to know how to answer this question, it has to be done all in MATLA

ID: 3847931 • Letter: I

Question

I would like to know how to answer this question, it has to be done all in MATLAB and I'm new to it so I am having a hard time figuring out how it's done.


(a) Write a function using for or while loop that computes an approximation to natural logarithm
function loge(1 + x) using the above formula. Your function must take x and n as function
input arguments. n is the number of terms you want to keep in your approximation. The
approximation will get more accurate if you keep more terms.


(b) Re-write your function using vectorization techniques.


(c) Determine the minimum number of terms you need to approximate loge(0.5) = -0.69314718 to
eight decimal digits? Print out your result on the screen as follows:
"It takes n=1000 terms to approximate log(0.5) = -0.69314718 to six digits, the approximation
is -0.693147179453401."


(d) Compute the error in the approximation to log(0.5) = -0.69314718 using n = 1, 5, 10, 25, 50, 100, 1000
terms in the above formula. Print a nice table of the results as follows:

n Approximation Error 1 -0.500000000000000 1.931471800000000e-01 5 ... 10 ... 25 ... 50 ... 100 ... 1000 ... In g2z3 14 T" n+1 I--+-+-+... n !

Explanation / Answer

(a)

create a file mylog.m and paste below code in it:

function [s] = mylog(x,n)
s = 0;
i = 1;
for i = 1:n
term = ((-1)^(i+1))*(x^i)/i;
s = s + term;
end
end

Sample Run:

(c)

Matlab code:

format long;
actual = -0.69314718;
i = 2;
while(abs(actual - mylog(-0.5,i)) >= 10^-8)
i = i + 1;
end
out = mylog(-0.5,i);
i
fprintf('It takes n = %d terms to approximate log(0.5) = -0.69314718 to eight digits and the approximation is ',i);
out

Sample Output:

(d)

Matlab code:

format long;
actual = -0.69314718;
n = [1, 5, 10, 25, 50, 100, 1000];

for i = 1:size(n,2)
out = mylog(-0.5,n(i));
error = abs(actual - out);
fprintf('%d %d %d ',n(i),out,error);
end

Sample Output:

(b)

function [s] = mylog(x,n)
    format long;
    syms k
    s = symsum( ((-1)^(k+1))*(x^k)/k , k, 1, n);   
end