Having trouble with Taylor Series summation

1 次查看(过去 30 天)
I'm estimating the value of sin(x) using the summation form of the sin(x) taylor series. I'm supposed to sum the first 250 terms terms but I'm getting NaN. This code worked fine for the first 100 and didn't read NaN until after the first 220 terms. Is there another way around this?
a20 = input('Input a value for X');
aSum2 = 0;
for j = 0:250 %Sums first 220 terms !!!After 220 Matlab reads "NaN"
%adds a23 to aSum for every itteration
a23 = ((-1)^j*a20^(2*j+1))/(factorial(2*j+1));
aSum2 = aSum2+a23;
end
disp(aSum2);

回答(1 个)

John D'Errico
John D'Errico 2017-4-22
编辑:John D'Errico 2017-4-22
Why do you think you were told to compute 250 terms?
What is a20? By the way, it is a REALLY bad idea to use numbered variables like that. You have a20, a23, etc. Those variables have little in common, except that they are in the same program. If you continue down this line, you will soon be in programming hell, with completely unreadable, un-debuggable code.
Regardless, what is the value of a20^(2*221 + 1) ? Since I have no idea what a20 is, how can I know?
What is the value of factorial(2*221 + 1) ? I'll help you out here.
factorial(2*221 + 1)
ans =
Inf
Next, what happens when you try to compute that ratio?
Never just write a formula without thinking about what you are trying to compute. When you get garbage, look at the terms in that formula.
Next, can you compute each term in that series from the previous one? (Of course you can.) You never need to compute a factorial at all, IF you think about the relationship between successive terms.
So, go back to the formula for a factorial, and figure out the relationship between
a20^(2*j+1)/factorial(2*j + 1)
and
a20^(2*(j-1)+1)/factorial(2*(j-1) + 1)
Come on. You need to think, as this is a key part of what you need to do. I've already told you a huge amount, so now it is your turn.
  2 个评论
Samuel Temes
Samuel Temes 2017-4-23
I use those odd variable names because of the nature of my homework. We have multiple sections that we have to turn in, in the same file (ex; question a sub-question 2 variable 1: a21). I wouldn't code like that normally. At the risk of sounding stupid, can you clarify what you mean by the factorial relationship you're talking about? I'm probably overthinking it.
Torsten
Torsten 2017-4-24
Use
a20^(2*(j+1)+1)/(factorial(2*(j+1)+1)) =
a20^(2*j+1)/factorial(2*j+1) * a20^2/((2*j+2)*(2*j+3))
Best wishes
Torsten.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by