For loops: initialize the sum variable

2 次查看(过去 30 天)
For this code if put the initial value of sum=1 then I get different answer.But I thought the inital values of sum doesn't matter? Can anyone explain?
m = input('Please enter the number of terms in the sum: ');
n = 0;
SUM = 0;
disp(' ')
for n = 1:m
an = (-1/3)^n/(2*n + 1);
SUM = SUM + an = (-1/3)^n/(2*n + 1);
Val_Exp = sqrt(12)*SUM;
Prec_pi = abs(pi-Val_Exp);
fprintf('For n = %2i, Value = %.15f to a precision of %.10e.\n', n, Val_Exp, Prec_pi)
end disp(' ')

回答(1 个)

Walter Roberson
Walter Roberson 2019-12-9
SUM = SUM + an = (-1/3)^n/(2*n + 1);
That is invalid syntax. You cannot have two = in the same statement.
end disp(' ')
That is invalid syntax. You need a statement separator between end and what follows.
Why whould you think that the initial values did not matter?
I would suggest to you that what you missed is that your summation is really over 0 to m instead of 1 to m, and that there are two ways you can compute that: you can either initialize the sum to 0 and loop from 0, or you can initialize the sum to 1 and loop from 1. Either way works because the term for n = 0 works out to 1.

类别

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