MATLAB How to Use Loops in MATLAB for Maclaurin Series Approximation?

AI Thread Summary
The discussion focuses on using loops in MATLAB to approximate cos(x) using the Maclaurin series. The user seeks advice on simplifying their code by implementing for or while loops instead of manually calculating each term. Key points include the need for accuracy to 8 significant digits and the derivation of the error tolerance, epsilon_s. Suggestions emphasize leveraging MATLAB's matrix manipulation and the importance of reusing previous terms in the series to streamline calculations. Overall, the conversation highlights best practices for coding in MATLAB while tackling mathematical approximations.
ibjeepn247365
Messages
1
Reaction score
0
Hi, hopefully you guys can point me in the right direction. The problem says to determine the number of terms necessary to approximate cos(x) to 8 significant digits using Maclaurin series approximation for x = .3*pi. I don't really have a problem with the actually question, my problem comes when we have to do this in matlab. I have come up with something in MATLAB that gives me the answer but wondering if I could use a for or while loop to make it shorter because it seems like there is another way to do it. Thank you for your help in advance. This is a rough copy of MATLAB and just to see if I got the right anser.
n = 8; %Significant Digits
x = .3*pi;
format long
epsilon_s = (.5*10^(2-n));
maclaurin_1 = 1;
maclaurin_2 = 1 - x^2/2;
maclaurin_3 = 1 - x^2/2 + x^4/factorial(4);
maclaurin_4 = 1 - x^2/2 + x^4/factorial(4) - x^6/factorial(6);
maclaurin_5 = 1 - x^2/2 + x^4/factorial(4) - x^6/factorial(6) + x^8/factorial(8);
maclaurin_5 = 1 - x^2/2 + x^4/factorial(4) - x^6/factorial(6) + x^8/factorial(8)...
-x^10/factorial(10);
maclaurin_6 = 1 - x^2/2 + x^4/factorial(4) - x^6/factorial(6) + x^8/factorial(8)...
-x^10/factorial(10) + x^12/factorial(12);
epsilon_a_1 = (maclaurin_2 - maclaurin_1)/maclaurin_2;
epsilon_a_2 = (maclaurin_3 - maclaurin_2)/maclaurin_3;
epsilon_a_3 = (maclaurin_4 - maclaurin_3)/maclaurin_4;
epsilon_a_4 = (maclaurin_5 - maclaurin_4)/maclaurin_5;
epsilon_a_5 = (maclaurin_6 - maclaurin_5)/maclaurin_6;
if abs(epsilon_a_1) < epsilon_s
fprintf('True1\n');
end
if abs(epsilon_a_2) < epsilon_s
fprintf('True2\n');
end
if abs(epsilon_a_3) < epsilon_s
fprintf('True3\n');
end
if abs(epsilon_a_4) < epsilon_s
fprintf('True4\n');
end
if abs(epsilon_a_5) < epsilon_s
fprintf('True5\n');
end
 
Physics news on Phys.org
I would properly take a little advantage of matlabs matrix manipulation:
Code:
n = 8; %Significant Digits
x = .3*pi;
epsilon_s = (.5*10^(2-n));
Res(1,1) = 1;
Res(2,1) = 1 - x^2/2;
Res(3,1) = 1 - x^2/2 + x^4/factorial(4);
Res(4,1) = 1 - x^2/2 + x^4/factorial(4) - x^6/factorial(6);
Res(5,1) = 1 - x^2/2 + x^4/factorial(4) - x^6/factorial(6) + x^8/factorial(8);
Res(6,1) = 1 - x^2/2 + x^4/factorial(4) - x^6/factorial(6) + x^8/factorial(8) -x^10/factorial(10);
Res(7,1) = 1 - x^2/2 + x^4/factorial(4) - x^6/factorial(6) + x^8/factorial(8) -x^10/factorial(10) + x^12/factorial(12);
for i = 1:6
Res(i,2) = (Res(i+1,1) - Res(i,1))/Res(i+1,1);
Res(i,3) = Res(i,2) - epsilon_s;
end
disp('      maclaurin_i           e_i               e_i-e_s')
disp(Res)
for j = 1:6
if abs(Res(j,2)) < epsilon_s
disp('Error is OK for i ='); disp(j)
end
end
 
Code:
clear all; 
n = 8; %Significant Digits
x = .3*pi;
format long
epsilon_s = (.5*10^(2-n));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
epsilon = 100; maclaurin(1) = 1;
i=1;
while epsilon > epsilon_s  % Loop until the error is small enough
i=i+1;
% use the actual formula since we have the first n-1 terms in the sum already
maclaurin(i) = maclaurin(i-1) + (-1)^(i-1)*x^(2*(i-1))/factorial(2*(i-1));
epsilon = abs((maclaurin(i)-maclaurin(i-1))/maclaurin(i));
end
disp(['Error is OK for i = ', num2str(i)]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Better to use the actual formula for the expansion than type out every term, otherwise you may make a typo as you did in the 5th term. And since you reuse the first n-1 terms each time, just take the previous answer and add one new term to it to simplify things.
 
hey guys anyone reply me the solution for the below problem ASAP.
can i ve a program to find the perfect numbers using this relationship
Mp=2^p-1 where Mp is the mersenne prime and p is the integer and the relationship related to perfect number is n=0.5(Mp+1)Mp=[2^(p-1) ]*((2^p)-1)
 
Where do you get the epsilon_s= (.5*10^(2-n)); from?
 
you mean you need someone to show you how to generally define the Maclaurin Series coefficient so you can implement your partial sum as the previous loop's sum plus another term?
 
Well, it looks like that epsilon_s term is some kind of tolerance for the accuracy. How was that expression derived?
 
I will show you all the program. I hope you found it interesting. Really, I am a new user of matlab, but also, i needed make it of homework. I have done it in spanish because I am mexican.


PROBLEMA:
Determinar las series de Maclaurin de las funciones f(x)=Seno(x) y g(x)=Coseno(x). ¿Cuantos términos se requieren para representar f(x) y g(x)?, dentro del intervalo -5<=x<=5, con un error inferior a 0.001

EXPLICACION DEL CODIGO ELABORADO:

1.-La funcion a la que se pretende obtener el polinomio de maclaurin es denominada fx. Cabe recordar que esta funcion debe ser trigonometrica, logaritmica o exponencial, para que se forme en todos los terminos de la serie el polinomio.

2.- Se recomienda que el numero inicial de terminos que se den a la serie sea de máximo 5. Si, por ejemplo realiza la primer corrida del programa, con n=4, y el resultado es n=4, puede ser que para ese valor de n terminos del polinomio, sean mas de los necesarios para adquirir la tolerancia deseada. Se esto sucede se recomienda probar con un número de "n" menor.

3.- "C" es el valor del punto en el cual se evalua la proximidad (tolerancia) del polinomio y la funcion original. Recordar que la serie de Maclaurin es un caso particular de la serie de Taylor en x=0. Por este motivo no es necesario agregar otro punto, you una serie de maclaurin siempre es simétrica con respecto al eje "y".

IMPORTANTE:

La capacidad del programa elaborado es limitada, debido a la cantidad de terminos que se involucran en los factoriales cada vez que crece la serie.

CODIGO EN MATLAB:

clf,
clear screen,
syms('x','y','fx','fxm','gh','fnx');
%%%%%%%%%%%%%%%%%%%%% D A T O S D E E N T R A D A %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fx=cos(x);%ESTA ES LA FUNCION EN LA FUNCION A LA CUAL SE LE OBTIENE LA SERIE DE MACLAWRIN
n=5;%ESTE ES EL NÚMERO INICIAL DE TERMINOS DE LA SERIE (MENOS DE 5)
c=6;%PUNTO EN EL CUAL SE EVALÚA EL ERROR)
tolerancia=.001;%TOLERANCIA PERMITIDA PARA EL POLINOMIO (EN EL PUNTO C)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fnx(1,1)=subs(fx,0);
gh(1,1)=subs(fx,0);
for i=1:n
fnx(i+1,1)=(diff(fx,i))/(factorial(i)), gh(i+1,1)=(subs(fnx(i+1,1),0))*x^i,
end
fxm=sum(gh);
d=abs(subs(fxm,c));
e=abs(subs(fx,c));
error=abs(d-e),
while error > tolerancia
n=n+1
fnx(n,1)=((diff(fx,n))/(factorial(n))),
gh(n,1)=((subs(fnx(n,1),0))*x^n);
fxm=sum(gh),
d=abs(subs(fxm,c)),
e=abs(subs(fx,c)),
error=abs(d-e)
end
f1=-(abs(c)+1);f2=abs(c)+1;
f=f1:0.1:f2;f3=subs(fx,x,f);
ezplot(fxm,f); hold on;
plot(f,f3,'m'),
clc
disp(' este es el polinomio de Maclaurin ')
pretty(fxm)
disp('el número de términos requeridos para la serie son'),n
error
legend('serie de Maclaurin','Función original')


SALUDOS DESDE MEXICO
 
factorial in matlab
 

Similar threads

Replies
10
Views
3K
Replies
4
Views
1K
Replies
5
Views
2K
Replies
1
Views
2K
Replies
2
Views
3K
Replies
2
Views
2K
Back
Top