MATLAB
write your own functions (5 of them) using for loop for
a) 1/(1-x),
b) e^x,
c) cos(x),
d) sin(x), and
e) ln(1+x)
do not use built-in factorial, or sine, cosine, log, and tangent functions.
%%%question 1
% 1/(1-x) =1-x+x^2-x^3+x^4-x^5+......+(-x)^n +....infinite
terms
function o=my_fun_question1(x)
o=0;
n=1000; %keep n very large
for i=0:n
o=o+(-x)^n;
end
end
%%%% question2
%% e^x= 1+x/1! +x^2/2!+ x^3/3!+....infinite terms
function o=my_fun_question2(x)
o=0;
n=1000; %keep n very large
prev_term=1;
o=prev_term;
for i=1:n
o=o+prev_term*(x/i);
prev_term=prev_term*(x/i);
end
end
%%%%%question 3
%%% cos x =1-x^2/2! +x^4/4! -x^6/6!+....
function o=my_fun_question3(x)
o=0;
n=1000; %keep n very large
prev_term=1;
o=prev_term;
for i=1:n
o=o+prev_term*((-1)^i )*(x*x/((2*i-1)*(2*i)));
prev_term=prev_term*(x*x/((2*i-1)*(2*i)));
end
end
%%%%%question 4
%%% sin x =x-x^3/3! +x^5/5! -x^7/7!+....
function o=my_fun_question4(x)
o=0;
n=1000; %keep n very large
prev_term=x;
o=prev_term;
for i=1:n
o=o+prev_term*((-1)^i )*(x*x/((2*i)*(2*i+1)));
prev_term=prev_term*(x*x/((2*i)*(2*i+1)));
end
end
%%%%%question 5
%%% ln 1+x = x-x^2/2 + x^3/3 +....
function o=my_fun_question5(x)
o=0;
n=1000; %keep n very large
for i=1:n
o=o+((-1)^(i+1))*(x^i)/i;
end
end
my_fun_question1(1/2)
my_fun_question2(1)
my_fun_question3(0)
my_fun_question4(0)
my_fun_question5(0)
Get Answers For Free
Most questions answered within 1 hours.