PDA

View Full Version : Trying to learn matlab (Taylor Series)


kalen
23 Oct 2007, 07:46pm
I'm supposed to be writing some code in matlab that will allow me to solve the Taylor series of e^x to a minimum term value of M.

The taylor series is
e^x= 1 + x/1! + x^2/2! +.....

I've been using matlabs help and google for about 6 hours trying to figure this out.

x=input('You are computing e^x, what number is x?');
d=input('What degree of accuracy would you like?');


c=0;
for b=0:1:1100
while b/(x^b/factorial(b))>1
c=c+((x^b)/factorial(b));

end
disp(sum(c))
end



I thought that this would cause it to set c as 0. Then run integers in order (1,2,3..) until it reached an answer that was less than the specified d value. Then it would stop and display the total of those values.

This isn't working and I can't figure out what I'm doing wrong.
Help, Please!

drasnor
23 Oct 2007, 08:45pm
First off, that is a Maclaurin series expansion for e^x which is equivalent to the Taylor series expansion of e^x about a=0. Just letting you know in case a is not necessarily 0 (see MathWorld entry on Taylor series (http://mathworld.wolfram.com/TaylorSeries.html).)
Questions:
What are the variables 'b', 'c', and 'd' supposed to do? You take 'd' as an input but never use it for anything.
You talk about M but what is M in terms of the code you created?

-drasnor :fold:

drasnor
24 Oct 2007, 03:01am
This code is provided for educational purposes only.
disp('Icrontic.com MATLAB Team Sample Code.');
disp('Copy at your own peril, many teachers/professors are proficient with Google.');
disp('This code evaluates a Taylor series approximation of e^x about the point a=0.');

% Variable definitions:
% x: power of e to be solved.
% d: desired accuracy evaluated as the value of the n-term Taylor series
% approximation - the (n-1)-term Taylor series approximation.
% n: number of terms in the Taylor series.
% t_n: nth term in Taylor series.
% e_approx: solution to the n-term Taylor series.

x=input('Enter x: ');
d=input('Enter accuracy of approximation: ');

n=1; % approximation begins with single-term solution
t_n=x^(n-1)/factorial(n-1);
e_approx=t_n; % initial approximation
while t_n > d % accuracy reached?
n=n+1; % add another term.
t_n=x^(n-1)/factorial(n-1); % evaluate the new term.
e_approx=e_approx+t_n; % add the new term to the approximation.
end
disp('Approximate solution of e^x:');
disp(e_approx);
disp('Number of terms in Taylor series:');
disp(n);
disp('Accuracy achieved:');
disp(t_n);

-drasnor :fold:

shwaip
24 Oct 2007, 03:25am
i swear we've had this exact question before.

moved to matlab help subforum

kalen
25 Oct 2007, 02:46am
Drasnor, thanks a ton man I think I understand what I was doing wrong,
Seeing your code really helped me understand how to approach it.

Thanks again.