I have this code to develop the partial sum of (1/k^2). However, when I run the code, the while loop does not stop. Any help with this problem?
function [sum1,error,steps] = psum(tol)
k=1;
sum1=1/(k).^2;
answer=(pi.^2)/6;
error=abs(answer-sum1);
while error>tol
k=1/(k+1)^2;
term=sum1+(1/(k).^2);
sum1=sum1+term
error=abs(answer-sum1)
end
steps=k

 채택된 답변

James Tursa
James Tursa 2016년 11월 14일
편집: James Tursa 2016년 11월 14일

0 개 추천

You are corrupting the value of k and not doing the term summing properly. These lines:
k=1/(k+1)^2;
term=sum1+(1/(k).^2);
should be this instead:
k = k + 1;
term=(1/(k).^2);
SIDE NOTE: "error" is the name of an intrinsic MATLAB function, so it would be best to use a different name for your variable (e.g., err).

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

질문:

2016년 11월 14일

편집:

2016년 11월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by