Way to decrease the step size in the while loop.
35 ビュー (過去 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!