0

I wrote a while loop that would keep on dividing an integer by $2$, and to stop when the result is equal to $0$, the the last result was $5\times 10^{-324}$. Then $0$. Why is this so ?, the value reached is still divisible by $2$ and should result in a smaller number. I would expect the number to get smaller and smaller.

let i = 4;
while(i!==0)
{  i = i/2;
   console.log(i);
}
  • Are you sure it's $10^{324}$ and not, say, $10^{-324}$? Remember, the result of repeatedly halving an integer will never be equal to $0$ unless some kind of underflow occurs in computation. – Patrick Stevens Dec 04 '16 at 10:28
  • u are correct, sorry about that fixed it – Osama Salama Dec 04 '16 at 10:29
  • exactly the result should never reach 0, that's why I tested it by running this js code. – Osama Salama Dec 04 '16 at 10:31
  • Isn't it completely obvious that this can't happen if you use a computer since they have finite memory and therefore cannot distinguish infinitely many different numbers? – Lukas Betz Dec 04 '16 at 10:37

1 Answers1

3

Computers have finite memory. If you have an extremely small number, it will also take an extremely large amount of memory to represent in a conventional form. Imagine the number $0.0000\dots01$, with $10^{100}$ zeroes where the dots are. That's a much larger number than your computer can fit into its memory.

Consequently, computers have to represent numbers in some way, and we have to choose how many bytes of memory we allocate to these objects. In particular, we usually represent numbers using the floating point format.

You may find this, in particular, to be relevant:

On a typical computer system, a 'double precision' (64-bit) binary floating-point number has a coefficient of 53 bits (one of which is implied), an exponent of 11 bits, and one sign bit. Positive floating-point numbers in this format have an approximate range of $10^{−308}$ to $10^{308}$.

So it looks like you got to a number so small that it could no longer be represented in your programming language's floating point format. Consequently, it got rounded to zero! (Depending on your language, it's also possible that it got set to zero as a result of some other policy on how to deal with exceptional numbers).

Newb
  • 17,672
  • 13
  • 67
  • 114