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
AI Thread Summary
The MATLAB while loop outputs 9.007199254740992e+15 due to floating-point precision limitations. As x increases, the expression (x+1)-x remains equal to 1 until x reaches a value where adding 1 does not change its representation, specifically at 2^53. This occurs because the mantissa of a double-precision number has 52 bits, leading to cancellation errors in arithmetic operations. Consequently, the loop continues to double x until it reaches this threshold, resulting in an unexpected output. Understanding the limitations of floating-point arithmetic is crucial for resolving such issues in MATLAB.
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?
 
  • Like
Likes 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) = ?
 
  • Like
Likes 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.
 
Back
Top