JavaScript Interview Question #185
What is Number.EPSILON?
Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
Number.EPSILON is the difference between 1 and the next representable Number value greater than 1. It is useful for understanding floating-point precision and can help in some approximate comparisons.
Detailed Explanation
Number.EPSILON is the difference between 1 and the next representable Number value greater than 1. It is useful for understanding floating-point precision and can help in some approximate comparisons.
A fixed EPSILON comparison is not a universal solution for every magnitude. Robust numerical code should choose a tolerance appropriate to the scale and domain of the values being compared.
Code Example
function nearlyEqual(a, b) {
return Math.abs(a - b) <
Number.EPSILON *
Math.max(1, Math.abs(a), Math.abs(b));
}
console.log(nearlyEqual(0.1 + 0.2, 0.3));