Way to decrease the step size in the while loop.
조회 수: 7 (최근 30일)
이전 댓글 표시
Hello,
belows are my code that find the 'Q' value which 'S' meets the tolerance of 0.1 % relative error.
I hava some issue when the step size (which is 1 for now) is too large, it repeats back and forth sometimes.
for example, Q is 101, 100, 101, 100, 101 ... without converge.
In that case, I want to decrease the step size 1 to 0.5 (for example). But I have no idea how to do that.
Please give me an insight !
while abs((S(801,1)-1000)/1000)>0.001
fprintf(' Q finding \n')
if S(801,1) > 1000 && abs((S(801,1)-1000)/1000)>0.001
Q = Q - 1;
Calcilation code
elseif S(801,1) < 1000 && abs((S(801,1)-1000)/1000)>0.001
Q = Q + 1;
Calcilation code
elseif abs((shoreline(801,1)-1000)/1000) < 0.001
end
end
댓글 수: 2
Jan
2023년 3월 13일
편집: Jan
2023년 3월 13일
Please use the tools for formatting code in the forum. Thanks.
What happens for S(801,1) == 1000 and abs((S(801,1)-1000)/1000) == 0.001? You get an infinite loop. Another strange formulation:
s = S(801, 1); % simpler code
s < 1000 && abs((s-1000)/1000)>0.001
% is equivalent to:
s < 1000 && abs((s-1000)) > 1
% is equivalent to:
s < 1000 && (s > 1001 || s < 999)
% is equivalent to:
s < 999
The code can and should be simplified.
A fixed increment cannot produce a convergence. Use Newton method instead.
Cameron
2023년 3월 13일
This code looks incomplete. How are you getting out of the loop? What is the variable "shoreline"? What is Q? You're not updating S(801,1) every iteration so if you get into the while loop you'll never get out.
답변 (1개)
Dinesh
2023년 4월 6일
Hi Minsik.
You can introduce a variable called "stepSize" within the for loop which equals to 1 or 0.5.
At the beginning of every iteration of the while loop, you can check if the values are not converging. If they are not, then you can change the "stepSize" accordingly, in this case you can change it to 0.5.
if <condition>
stepSize = 0.5;
end
Then, you can increment/decrement the value of 'Q' by the "stepSize" variable in the corresponding conditional statements.
Q = Q - stepSize; // or Q = Q + stepSize;
But as I can see the loop itself, it doesn't look correct to be because it would just run infinitely since the value of S(801,1) remains the same. You might have to update the value of S(801,1) every time the loop iterates to prevent this problem.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!