Displaying output from a summation.

조회 수: 1 (최근 30일)
Edward Steen
Edward Steen 2015년 10월 5일
댓글: Edward Steen 2015년 10월 5일
I'm trying to find partial sums of s=1/k^2 where k= multiples of 400. I'm using a "for" statement and want to have the script output the values at those multiples. At this point, I can only get it to output the final value. I want it to output the sums for k=400, 800, 1200, ... Also, I would like the output for the error for the actual sum.
Code is below.
format long
s=0;
for n=1:13
k=400;
end
for i=1:n*k
s=s+1/i^2;
y=abs(s-(pi^2/6));
end
disp([' Error', ' s_n'])
disp([y,s])
Thanks.

채택된 답변

Jan
Jan 2015년 10월 5일
편집: Jan 2015년 10월 5일
fprintf('%20s%20s\n', 'Error', 's_n');
s = 0;
n = 13; % The FOR loop is meaningless?!
k = 400;
r = pi^2/6;
for i = 1:n*k
s = s+1/i^2;
if mod(i, 400) == 0
y = abs(s-r);
fprintf('%20g%20g\n', y, s);
end
end
  댓글 수: 1
Edward Steen
Edward Steen 2015년 10월 5일
Thanks Jan! Very nice: so mod(i,400)==0 tells the script to only display the sum for multiples of i=400. The other thing I would like is for the script to run for n= some undetermined number but stop when y<.0002. So when the error is less than that, the script stops. Does a "while" loop make sense?
Thanks.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by