What happens to an integer number if I keep dividing it by 2?

778 Views Asked by At

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);
}
1

There are 1 best solutions below

0
On BEST ANSWER

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).