Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

max integer value in JavaScript

I'm reading the second chapter of the book Eloquent JavaScript. The author states that:

Any whole number less than 2^52 (which is more than 10^15) will safely fit in a JavaScript number.

I grabbed the value of 2^52 from wikipedia.

4,503,599,627,370,496

The value has to be less than 2^52, so I've substracted 1 from the initial value;

var max = 4503599627370495;

After defining the max variable I'm checking what's the value (I'm using Chrome 32.0.1700.77).

console.log(max); // 4503599627370495

I'd like to see what happens when I go over this limit, so I'm adding one a couple of times.

Unexpectedly:

max += 1;
console.log(max); // 4503599627370496
max += 1;
console.log(max); // 4503599627370497
max += 1;
console.log(max); // 4503599627370498

I went over the limit and the calculations are still precise.

I tried the next power of two instead, 2^53, I didn't substract 1 this time:

9,007,199,254,740,992

var max = 9007199254740992;

This one seems to be a bigger limit, it seems that I can quite safely add and substract numbers:

max += 1;
console.log(max); // 9007199254740992
max += 1;
console.log(max); // 9007199254740992
max -= 1;
console.log(max); // 9007199254740991
max += 1;
console.log(max); // 9007199254740992
max -= 900;
console.log(max); // 9007199254740092
max += 900;
console.log(max); // 9007199254740992

I can assign even a bigger value to the max, however it loses precision and I can't safely add or substract numbers again.

Could you please explain precisely the mechanism that sits under the hood? An example of what happens with the bits after going above 2^52 would be really helpful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is not a strongly typed programming language. JS has an object Number. You can even get an infinite number: document.write(Math.exp(1000));.

document.write(Number.MIN_VALUE + "<br>");
document.write(Number.MAX_VALUE + "<br>");

document.write(Number.POSITIVE_INFINITY + "<br>");
document.write(Number.NEGATIVE_INFINITY + "<br>");

    alert([
         Number.MAX_VALUE/(1e293),
         Number.MAX_VALUE/(1e292),
         Number.MAX_VALUE/(1e291),
         Number.MAX_VALUE/(1e290),
    ].join('
'))

Hope it's a useful answer. Thanks!

UPDATE: max int is - +/- 9007199254740992


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...