Taylor Series for e^x with while loop

I am attempting to write a code that will use a while loop to add terms of a taylor series approximation for e^x to a return value called "sum". I am trying to get the while loop to continue until the value of sum does not change after adding a new term. My main question is what term could I use to start the while loop? Should I have it be
while sum(i) ~= sum(i - 1)
end

1 comentario

James Tursa
James Tursa el 2 de Oct. de 2020
Editada: James Tursa el 3 de Oct. de 2020
Best to use a different variable name than sum, since sum is a standard MATLAB function. E.g., mysum.
Just give mysum(1) and mysum(2) the first two sums of the Taylor series and start i at 2.
That being said, you will not get good results with this as x gets larger, particularly when negative. The intermediate terms can grow hugely before the factorial in the denominator starts to dominate and the terms settle down. In the meantime you will get large cancellation errors in the intermediate sums.

Iniciar sesión para comentar.

Respuestas (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov el 3 de Oct. de 2020
x = 1.5;
SUM = 0;
ANS = exp(x);
Err = ANS-SUM;
Err_Margin = 1e-9;
ii=0;
while Err > Err_margin
ii=ii+1;
SUM(ii+1) = SUM(ii)+...
ERR = ANS-SUM(ii+1);
end

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 2 de Oct. de 2020

Respondida:

el 3 de Oct. de 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by