Why Doesn't My MATLAB While Loop Output the Expected Number?

  • Thread starter Thread starter ver_mathstats
  • Start date Start date
  • Tags Tags
    Loop Matlab
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 2K views
ver_mathstats
Messages
258
Reaction score
21
Homework Statement
Here is some Matlab code:
x = 1;
while (x+1)-x == 1
x = 2*x;
end
x
Explain why it terminates and explain why it outputs: 9.007199254740992e+15.
Relevant Equations
matlab, loops
I am confused why this is the case, why would it output that number? When I go through the code, there is (x+1)-1 which does equal 1, then x = 2*x is 2? So why is the output not 2? How should I proceed in coming up with a solution? Does this have something to do with cancellation errors somewhere?
 
Physics news on Phys.org
ver_mathstats said:
Homework Statement:: Here is some Matlab code:
x = 1;
while (x+1)-x == 1
x = 2*x;
end
x
Explain why it terminates and explain why it outputs: 9.007199254740992e+15.
Relevant Equations:: matlab, loops

I am confused why this is the case, why would it output that number? When I go through the code, there is (x+1)-1 which does equal 1, then x = 2*x is 2? So why is the output not 2? How should I proceed in coming up with a solution? Does this have something to do with cancellation errors somewhere?
In your code, x is evidently a double. What's the largest double-precision number that can be represented? What would that number + 1 be?
 
Reply
  • Like
Likes   Reactions: ver_mathstats
(x+1)-x will be equal to 1, until the addition of one to x fails to make a change.
The mantissa of a double has 52 bits plus one implied set bit.
2^(52+1) = ?
 
Reply
  • Like
Likes   Reactions: ver_mathstats
Baluncore said:
(x+1)-x will be equal to 1, until the addition of one to x fails to make a change.
The mantissa of a double has 52 bits plus one implied set bit.
2^(52+1) = ?
Okay, I see, I think I'm understanding much better
 
Mark44 said:
In your code, x is evidently a double. What's the largest double-precision number that can be represented? What would that number + 1 be?
Because 2^53=9.007199254740992e+15 and (2^53)+1=9.007199254740992e+15
 
Addition and subtraction of floating point numbers requires the exponents first be made equal. The smaller number may become zero during the justification shift of the mantissa, before the arithmetic step. The arithmetic will then make no change to the bigger number.