Analyzing while loop in matlab

  • Thread starter ver_mathstats
  • Start date
  • Tags
    Loop Matlab
In summary, x is a double-precision number that might have a number that is too large to be represented and when it is added to 1 it doesn't change the value.f
  • #1
260
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?
 
  • #2
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
  • #3
(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
  • #4
(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
 
  • #5
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
 
  • #6
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.
 

Suggested for: Analyzing while loop in matlab

Replies
1
Views
700
Replies
10
Views
831
Replies
6
Views
1K
Replies
1
Views
715
Replies
3
Views
532
Replies
10
Views
883
Replies
10
Views
671
Replies
1
Views
569
Back
Top