필터 지우기
필터 지우기

How to prevent addition from showing up in command window

조회 수: 1 (최근 30일)
Kyle Donk
Kyle Donk 2020년 1월 17일
편집: stozaki 2020년 1월 18일
I ran some code and am having trouble with the results of the code come out like this:
995
996
997
998
999
1000
How do I just get 1000 instead of all of the numbers? I have suppressed literally everything in the code.
  댓글 수: 3
Rik
Rik 2020년 1월 18일
Without a meaningful sample of your code, we can't give a meaningful solution.
Stephen23
Stephen23 2020년 1월 18일
Kyle Donk's "Answer" moved here:
N=10;
error=1;
while error>10^-4
N=N+1;
total=0;
for n=1:N;
y=1/n^2;
total=total+y;
end
error=((pi^2)/6)-total;
disp(N)
end

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

채택된 답변

stozaki
stozaki 2020년 1월 18일
편집: stozaki 2020년 1월 18일
If you get only 1000, you can try following script.
N=10;
err=1;
while err>10^-3
N=N+1;
total=0;
for n=1:N
y=1/n^2;
total=total+y;
end
err=((pi^2)/6)-total;
end
disp(N);
Is the intent of the question I understood fit?
 
Regards,
stozaki
  댓글 수: 2
Image Analyst
Image Analyst 2020년 1월 18일
Built in function names, like error and sum, should not be used as variable names.
Also not sure why you're printing out the iteration number in
fprintf('>> error value %d is over 10^3\n',N);
instead of the final error.
stozaki
stozaki 2020년 1월 18일
It was just a descriptive print statement. I'm sorry. I also prioritized leaving the questioner's code as much as possible.

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

추가 답변 (1개)

Image Analyst
Image Analyst 2020년 1월 18일
Try this:
numberOfTerms = 10;
maxIterations = 1000000; % To prevent infinite loops.
loopCounter = 1;
theError = 1;
while theError > 1e-4 && loopCounter < maxIterations
total = 0;
for n = 1 : numberOfTerms
y = 1 / n^2;
total = total+y;
end
theError = ((pi^2)/6) - total;
% Optional: print out the total and error at each iteration.
fprintf('After %d iterations, and using %d terms, the total is %f, and the error is %.9f.\n', ...
loopCounter, numberOfTerms, total, theError);
numberOfTerms = numberOfTerms+1;
loopCounter = loopCounter + 1;
end
% Print out the final results.
fprintf('The final error after the loop exited is %.9f.\n', theError);
You'll see
After 9989 iterations, and using 9998 terms, the total is 1.644834, and the error is 0.000100015.
After 9990 iterations, and using 9999 terms, the total is 1.644834, and the error is 0.000100005.
After 9991 iterations, and using 10000 terms, the total is 1.644834, and the error is 0.000099995.
The final error after the loop exited is 0.000099995.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by