필터 지우기
필터 지우기

Prevention of negative value in Iteration

조회 수: 7 (최근 30일)
Dhananjay Singh
Dhananjay Singh 2021년 8월 29일
댓글: Walter Roberson 2021년 8월 29일
What to change here such that final value never goes negative i.e (0<value<=0.00009) and x changes accordingly
x = 0.77;
maxIterations = 10000000; % Failsafe to prevent infinite loop
loopCounter = 0; % Failsafe to prevent infinite loop
value = (0.5-x);
while value >= 0.00009 && (loopCounter < maxIterations)
x = x + 0.0001;
value = (0.5-x);
loopCounter = loopCounter + 1; % Failsafe to prevent infinite loop
% fprintf('After %d iterations, x = %f and value = %f.\n', loopCounter, x, value);
end
fprintf('After %d iterations, x = %f and value = %f.\n', loopCounter, x, value);
After 0 iterations, x = 0.770000 and value = -0.270000.

채택된 답변

Walter Roberson
Walter Roberson 2021년 8월 29일
while value >= 0.00009 && (loopCounter < maxIterations)
newx = x + 0.0001;
newvalue = (0.5-newx);
if newvalue < 0.00009; break; end
x = newx;
value = newvalue;
loopCounter = loopCounter + 1; % Failsafe to prevent infinite loop
% fprintf('After %d iterations, x = %f and value = %f.\n', loopCounter, x, value);
end
  댓글 수: 4
Dhananjay Singh
Dhananjay Singh 2021년 8월 29일
that's what i am looking to find a value of x by iteration such that value is not negative and value is nearly equal to 0.
Walter Roberson
Walter Roberson 2021년 8월 29일
I suggest you use fzero() or fsolve()

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

추가 답변 (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