Emmanuel Akinfulubi

JavaScriptMath

Number.EPSILON and float tolerance in JavaScript

Intermediate · 4 min read

You know by now that 0.1 + 0.2 === 0.3 is false. The usual fix is to stop asking "are these exactly equal?" and ask "are these close enough?" instead. That is called comparing with a tolerance, and it is how test libraries, games and charting code compare decimals.

In this tutorial you will write close(a, b) with a fixed tolerance, find a pair of numbers where it gives the wrong answer, and fix it with closeRel(a, b), which scales the tolerance to the size of the numbers. You will also find out what Number.EPSILON really is. You need to know Math.abs and arrow functions.

Close enough

Two numbers are close if the distance between them is small. The distance is Math.abs(a - b), and "small" is a limit you choose, the tolerance. So:

JavaScript

const close = (a, b, tol = 1e-9) => Math.abs(a - b) < tol;
console.log(close(0.1 + 0.2, 0.3)); // true

1e-9 is short for 0.000000001, a billionth. tol = 1e-9 is a default value used when you don't pass a third argument.

What Number.EPSILON is

Number.EPSILON is a built-in constant, and many tutorials say to use it as the tolerance. It is actually something more specific: the gap between 1 and the very next number a double can store. Doubles are spaced out, and near 1 that spacing is EPSILON. Far from 1 the spacing is different, which is the key to this exercise.

Here is the exercise. Try it first if you like, then read on and we will build it step by step.

12 Number.EPSILON and comparing with a tolerance

fair

Write close(a, b) using an absolute tolerance, then closeRel(a, b) using a relative one, and find the input where the absolute version gives the wrong answer.

Stuck? Three hints, smallest first
  1. 1. Number.EPSILON is the gap between 1 and the next representable double.
  2. 2. An absolute tolerance of 1e-9 is meaningless at a magnitude of 1e16, where consecutive doubles are 2 apart.
  3. 3. A relative tolerance scales the allowance by the size of the numbers being compared.

Step 1: see the gap above 1

Step 1

console.log(Number.EPSILON);                  // 2.220446049250313e-16
console.log(1 + Number.EPSILON === 1);        // false
console.log(1 + Number.EPSILON / 2 === 1);    // true

Adding EPSILON to 1 moves to the next stored number. Adding half of it is too small to reach the next one, so the result rounds back to exactly 1. The half simply vanishes.

Step 2: where the fixed tolerance fails

Doubles get further apart as numbers get bigger. Around 10,000,000,000,000,000 (written 1e16), two neighboring doubles are 2 apart. There is no double for 1e16 + 1 at all.

Step 2

const close = (a, b, tol = 1e-9) => Math.abs(a - b) < tol;
console.log((1e16 + 2) - 1e16);   // 2
console.log(close(1e16, 1e16 + 2)); // false

These two numbers are as close as two different doubles can be at that size. Yet close says no, because 2 is much bigger than a billionth. At this size, asking for a gap under 1e-9 means asking for the numbers to be identical.

Step 3: scale the tolerance

A relative tolerance grows with the numbers. Instead of "within a billionth", it asks "within a billionth of the bigger number's size":

Step 3

const closeRel = (a, b, tol = 1e-9) =>
  Math.abs(a - b) <= tol * Math.max(Math.abs(a), Math.abs(b), 1);
console.log(closeRel(1e16, 1e16 + 2)); // true
console.log(closeRel(0.1 + 0.2, 0.3)); // true
console.log(closeRel(1, 1.1));         // false

For 1e16, the allowance is a billionth of 1e16, which is 10,000,000, so a gap of 2 passes. It still refuses 1 and 1.1, which really are different.

The 1 inside Math.max sets a floor. Without it, two numbers very near zero would get an allowance near zero, and you would be back to demanding exact equality.

Step 4: is EPSILON a good tolerance?

EPSILON is fine for a single addition near 1:

Step 4

const close = (a, b, tol = 1e-9) => Math.abs(a - b) < tol;
console.log(close(0.1 + 0.2, 0.3, Number.EPSILON)); // true

But errors build up. Add a thousandth a thousand times and the result should be 1:

JavaScript

let accumulated = 0;
for (let i = 0; i < 1000; i++) accumulated += 0.001;
console.log(accumulated);                              // 1.0000000000000007
console.log(Math.abs(accumulated - 1) < Number.EPSILON); // false

The thousand roundings added up to more than EPSILON, so the check fails even though the answer is as right as a loop of doubles can make it.

Step 5: choose a tolerance from the problem

The rule of thumb is to pick the tolerance from what the numbers mean, not from the machine. Money to the nearest kobo can use half a kobo, 0.005 naira. A geometry check can use a relative 1e-9. EPSILON describes how doubles are spaced near 1; it isn't a general-purpose "close enough".

The full solution

The answer panel defines close and closeRel, shows EPSILON vanishing when halved, compares the two functions at 1e16, and runs the thousand-step loop. The checks underneath confirm where each tolerance passes and fails. Press Run to see the output.

The answer

const close = (a, b, tol = 1e-9) => Math.abs(a - b) < tol;

const closeRel = (a, b, tol = 1e-9) =>
  Math.abs(a - b) <= tol * Math.max(Math.abs(a), Math.abs(b), 1);

// A thousand additions of a thousandth: the error is now wider than EPSILON.
let accumulated = 0;
for (let i = 0; i < 1000; i++) accumulated += 0.001;

console.log('EPSILON              :', Number.EPSILON);
console.log('1 + EPSILON === 1    :', 1 + Number.EPSILON === 1);
console.log('1 + EPSILON/2 === 1  :', 1 + Number.EPSILON / 2 === 1, '<- it vanished');
console.log('close(0.1+0.2, 0.3)  :', close(0.1 + 0.2, 0.3));
console.log('close(1e16, 1e16+2)  :', close(1e16, 1e16 + 2), '<- 2 apart, and adjacent doubles');
console.log('closeRel(1e16, +2)   :', closeRel(1e16, 1e16 + 2));
console.log('closeRel(1, 1.1)     :', closeRel(1, 1.1), '<- still refuses real differences');
console.log('1000 x 0.001         :', accumulated, 'off by', Math.abs(accumulated - 1));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('EPSILON is the gap above 1', Number.EPSILON, 2.220446049250313e-16);
test('adding it changes the number', 1 + Number.EPSILON === 1, false);
test('adding half of it does not', 1 + Number.EPSILON / 2 === 1, true);
test('an absolute tolerance settles 0.1 + 0.2', close(0.1 + 0.2, 0.3), true);
test('but at 1e16 two doubles differ by 2, so it says not close', close(1e16, 1e16 + 2), false);
test('a relative tolerance handles both magnitudes', [closeRel(0.1 + 0.2, 0.3), closeRel(1e16, 1e16 + 2)], [true, true]);
test('and still refuses genuinely different numbers', closeRel(1, 1.1), false);
test('EPSILON is wide enough for a single addition', close(0.1 + 0.2, 0.3, Number.EPSILON), true);
test('but too tight once a thousand additions have accumulated', close(accumulated, 1, Number.EPSILON), false);

Number.EPSILON is often described as "the tolerance to compare floats with", and the last assertion shows why that is wrong. It is the spacing of doubles near 1. Values that have been through several operations accumulate more error than that, and values far from 1 have a much wider spacing — near 1e16, consecutive doubles are 2 apart, so asking for agreement within 1e-9 is asking for bit equality.

The rule of thumb: pick a tolerance from the domain, not from the machine. Money to the kobo means 0.005; a geometry test means something like 1e-9 relative. The Math.max(..., 1) floor in closeRel keeps it sensible when both values are near zero, where a purely relative test would demand exactness.

Common mistakes

  • Using Number.EPSILON for every comparison. It is too tight once a value has been through many operations, and far too tight for large numbers.
  • Using a fixed tolerance for huge numbers. At 1e16, neighboring doubles are 2 apart. Use a relative tolerance.
  • Writing a - b < tol without Math.abs. Any negative difference passes, so close(0, 100) would say true.

Try it yourself

  1. Use closeRel to check 0.1 * 3 against 0.3.
  2. Write closeMoney(a, b) that treats two naira amounts as equal when they are less than half a kobo apart.
  3. Find the gap between neighboring doubles near 1e15 with (1e15 + 1) - 1e15. Then try 1e17.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.