For loops: initialize the sum variable

2 views (last 30 days)
Abida Islam
Abida Islam on 9 Dec 2019
Answered: Walter Roberson on 9 Dec 2019
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(' ')

Answers (1)

Walter Roberson
Walter Roberson on 9 Dec 2019
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.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!