필터 지우기
필터 지우기

How to calculate the Taylor series expansion of e^x

조회 수: 4 (최근 30일)
Scott
Scott 2016년 11월 11일
편집: John D'Errico 2016년 11월 11일
I need to implement a script that calculate the Taylor series expansion of e^x. There are two inputs: n = the number of terms in the expansions, and tolerance = basically the percent change in adding one more term.
In other words, the tolerance = | (sum_previous – sum_new) / sum_previous | < 0.000001
So the user inputs the number of terms to be added, and they specify a tolerance. I am not sure how to get the while loops to work correctly. Here's what I have so far:
old_sum = 1;
new_sum = 0;
steps = 0;
approx = 0;
i = 0;
while (abs((old_sum-new_sum)/(old_sum)))>= tolerance
old_sum = (x^i)/myFactorial(i);
new_sum = new_sum + old_sum;
i = i + 1;
steps = steps + 1;
end

채택된 답변

John D'Errico
John D'Errico 2016년 11월 11일
편집: John D'Errico 2016년 11월 11일
I changed things slightly. Look carefully at the changes I made.
tolerance = 0.000001;
old_sum = 1;
new_sum = 0;
current_term = inf;
iter = 0;
while abs(current_term/old_sum) >= tolerance
old_sum = new_sum;
current_term = (x^iter)/myFactorial(iter);
new_sum = new_sum + current_term;
iter = iter + 1;
end
steps = iter;
Note that the difference between the two approximations is the variable now named current_term. So I could have written the test to work on this:
abs((new_sum - old_sum)/old_sum)
but we know what the difference in the numerator is already.
As far as incrementing both i AND the variable steps, WHY? As well, it is a bad idea to use the variable i, since i already exists in MATLAB as sqrt(-1). Better to form good habits early in your career. So I changed i to iter.
I tested the code above. It works. But be careful, for large x, it will be a problem. You should know that already, if you have discussed convergence of series in class.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Calculus에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by