Does this 'for' loop stop, and why/why not? for (var i=0; 1/i > 0; i++) { }

后端 未结 3 1916
不思量自难忘°
不思量自难忘° 2021-01-29 22:03

Does this for loop ever stop?

for (var i=0; 1/i > 0; i++) {
}

If so, when and why? I was told that it stops, but I was given no r

3条回答
  •  不思量自难忘°
    2021-01-29 22:17

    Answer:

    The condition 1/i > 0 will always evaluate to true:

    • Initially it's true because 1/0 evaluates to Infinity and Infinity > 0 is true

    • It stays true since 1/i > 0 is true for all i < Infinity and i++ never reaches Infinity.

    Why does i++ never reach Infinity? Due to the limited precision of the Number datatype, there is a value for which i + 1 == i:

    9007199254740992 + 1 == 9007199254740992 // true
    

    Once i reaches that value (which corresponds to Number.MAX_SAFE_INTEGER + 1), it will stay the same even after i++.

    We therefore have an infinite loop.


    Appendix:

    Why is 9007199254740992 + 1 == 9007199254740992?

    JavaScript's Number datatype is actually an 64-bit IEEE 754 double precision float. Each Number is disassembled and stored as three parts: 1-bit sign, 11-bit exponent, and 52-bit mantissa. Its value is -1 sign × mantissa × 2 exponent.

    How is 9007199254740992 represented? As 1.0 × 2 53, or in binary:

    enter image description here

    Incrementing the mantissa's least significant bit, we get the next higher number:

    enter image description here

    The value of that number is 1.00000000000000022… × 2 53 = 9007199254740994

    What does that mean? Number can either be 9007199254740992 or 9007199254740994, but nothing in between.

    Now, which one shall we chose to represent 9007199254740992 + 1? The IEEE 754 rounding rules give the answer: 9007199254740992.

提交回复
热议问题