Prevention of negative value in Iteration

10 views (last 30 days)
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.

Accepted Answer

Walter Roberson
Walter Roberson on 29 Aug 2021
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 Comments
Dhananjay Singh
Dhananjay Singh on 29 Aug 2021
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 on 29 Aug 2021
I suggest you use fzero() or fsolve()

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!