For loops: initialize the sum variable

2 Ansichten (letzte 30 Tage)
Abida Islam
Abida Islam am 9 Dez. 2019
Beantwortet: Walter Roberson am 9 Dez. 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(' ')

Antworten (1)

Walter Roberson
Walter Roberson am 9 Dez. 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.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by