Number EPSILON Compares Floats Safely

Compare floats with a relative Number.EPSILON tolerance instead of ===, since binary rounding makes 0.1 + 0.2 differ from 0.3 by one resolution step.

JavascriptData Integrity

Code

javascriptsnippet
16 lines
// 浮点误差:0.1 + 0.2 !== 0.3,安全比较要用容差而不是 ===
const sum = 0.1 + 0.2;
console.log('sum      :', sum);
console.log('naive ===:', sum === 0.3);

// 相对容差:误差预算随数值大小按比例放大,EPSILON 是最小分辨率
function nearlyEqual(a, b, epsilon = Number.EPSILON) {
  return Math.abs(a - b) <= epsilon * Math.max(Math.abs(a), Math.abs(b), 1);
}

console.log('epsilon  :', nearlyEqual(sum, 0.3));
console.log('distinct :', nearlyEqual(1.5, 1.6));

// 内建数值守卫:整数判断与安全整数范围
console.log('isInteger:', Number.isInteger(42), Number.isInteger(42.5));
console.log('safe     :', Number.isSafeInteger(2 ** 53), Number.MAX_SAFE_INTEGER);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

sum      : 0.30000000000000004
naive ===: false
epsilon  : true
distinct : false
isInteger: true false
safe     : false 9007199254740991

What the code does

Number EPSILON Compares Floats Safely is built around the function nearlyEqual.

Applying it

The primary signature is function nearlyEqual(a, b, epsilon = Number.EPSILON)

The demo output is labeled (sum :, naive ===:, epsilon :), so every printed line maps back to its originating operation.

Statements that matter

return Math.abs(a - b) <= epsilon * Math.max(Math.abs(a), Math.abs(b), 1);

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `nearlyEqual` at load time.