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(' ')
댓글 수: 0
답변 (1개)
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!