精确到 1 位十进制数字,您可以使用的最大数字是 562949953421311。
精确到 2 位十进制数字,它是 70368744177663。
有趣的是,第一个数字等于:
(Number.MAX_SAFE_INTEGER + 1) / 16 - 1
而第二个数等于:
(Number.MAX_SAFE_INTEGER + 1) / 128 - 1
我们正在寻找,是支持小数点后d 位精度的最大安全数。
我所说的“支持”是指“可以可靠地进行基本算术”。
例如,我们知道Number.MAX_SAFE_INTEGER (aka 2**53-1) 是不安全的,因为基本算术被破坏了:
Number.MAX_SAFE_INTEGER - 0.1 === Number.MAX_SAFE_INTEGER
>>> true // unsafe
我们知道 0 是安全的,因为:
0 + 0.1 === 0
>>> false // safe
顺便说一句,就1e-323(包括)而言,0 是可靠的:
0 + 1e-323 === 0
>>> false // safe
0 + 1e-324 === 0
>>> true // unsafe
我在 0 和 Number.MAX_SAFE_INTEGER 之间进行二进制搜索,以找到符合该定义的最大数字,并得出这些数字。
这是代码(在 sn-p 末尾将任何其他数字传递给 findMaxSafeFloat())
/**Returns whether basic arithmetic breaks between n and n+1, to a precision of `digits` after the decimal point*/
function isUnsafe(n, digits) {
// digits = 1 loops 10 times with 0.1 increases.
// digits = 2 means 100 steps of 0.01, and so on.
let prev = n;
for (let i = 10 ** -digits; i < 1; i += 10 ** -digits) {
if (n + i === prev) { // eg 10.2 === 10.1
return true;
}
prev = n + i;
}
return false;
}
/**Binary search between 0 and Number.MAX_SAFE_INTEGER (2**53 - 1) for the biggest number that is safe to the `digits` level of precision.
* digits=9 took ~30s, I wouldn't pass anything bigger.*/
function findMaxSafeFloat(digits, log = false) {
let n = Number.MAX_SAFE_INTEGER;
let lastSafe = 0;
let lastUnsafe = undefined;
while (true) {
if (log) {
console.table({
'': {
n,
'Relative to Number.MAX_SAFE_INTEGER': `(MAX + 1) / ${(Number.MAX_SAFE_INTEGER + 1) / (n + 1)} - 1`,
lastSafe,
lastUnsafe,
'lastUnsafe - lastSafe': lastUnsafe - lastSafe
}
});
}
if (isUnsafe(n, digits)) {
lastUnsafe = n;
} else { // safe
if (lastSafe + 1 === n) { // Closed in as far as possible
console.log(`\n\nMax safe number to a precision of ${digits} digits after the decimal point: ${n}\t((MAX + 1) / ${(Number.MAX_SAFE_INTEGER + 1) / (n + 1)} - 1)\n\n`);
return n;
} else {
lastSafe = n;
}
}
n = Math.round((lastSafe + lastUnsafe) / 2);
}
}
console.log(findMaxSafeFloat(1));
我通过排列安全数字发现了一个有趣的事情,即指数不会以一致的方式递增。
请看下表;有时,指数增加(或减少)4,而不是 3。不知道为什么。
| Precision | First UNsafe | 2^53/x |
|-----------|-----------------------------|--------------------------|
| 1 | 5,629,499,534,21,312 = 2^49 | x = 16 = 2^4 |
| 2 | 703,687,441,77,664 = 2^46 | x = 128 = 2^7 |
| 3 | 87,960,930,22,208 = 2^43 | x = 1,024 = 2^10 |
| 4 | 5,497,558,13,888 = 2^39 | x = 16,384 = 2^14 |
| 5 | 68,719,476,736 = 2^36 | x = 131,072 = 2^17 |
| 6 | 8,589,934,592 = 2^33 | x = 1,048,576 = 2^20 |
| 7 | 536,870,912 = 2^29 | x = 16,777,216 = 2^24 |
| 8 | 67,108,864 = 2^26 | x = 134,217,728 = 2^27 |
| 9 | 8,388,608 = 2^23 | x = 1,073,741,824 = 2^30 |