3947

Consider the following code:

0.1 + 0.2 == 0.3  ->  false
0.1 + 0.2         ->  0.30000000000000004

Why do these inaccuracies happen?

13

34 Answers 34

1
2
3

I just saw this interesting issue around floating points:

Consider the following results:

error = (2**53+1) - int(float(2**53+1))
>>> (2**53+1) - int(float(2**53+1))
1

We can clearly see a breakpoint when 2**53+1 - all works fine until 2**53.

>>> (2**53) - int(float(2**53))
0

Enter image description here

This happens because of the double-precision binary: IEEE 754 double-precision binary floating-point format: binary64

From the Wikipedia page for Double-precision floating-point format:

Double-precision binary floating-point is a commonly used format on PCs, due to its wider range over single-precision floating point, in spite of its performance and bandwidth cost. As with single-precision floating-point format, it lacks precision on integer numbers when compared with an integer format of the same size. It is commonly known simply as double. The IEEE 754 standard specifies a binary64 as having:

  • Sign bit: 1 bit
  • Exponent: 11 bits
  • Significant precision: 53 bits (52 explicitly stored)

Enter image description here

The real value assumed by a given 64-bit double-precision datum with a given biased exponent and a 52-bit fraction is

Enter image description here

or

Enter image description here

Thanks to @a_guest for pointing that out to me.

2

Simply ignore the all the nitty-gritty and just think of numeric bases like different geometric shapes—circles, squares, triangles, hexagons, trapezoids (multi-dimensional shapes too), etc.

  • Say one kind of rectangle has a 3:1 aspect ratio vs. a square — you can fit three squares exactly in that rectangle. The equivalent in the analogy would be larger shape (base) being an integer power of the smaller base,

    like 2 vs. 8 = 2 x 2 x 2

And similarly, three of those rectangles stacked on top of each other makes a perfect square that's nine times the area of the original square, which you can also confirm pseudo-mathematically:

2 ^ 9 = 512 = 8 ^ 3

--- (again, this is a different type of non-euclidean analogy, not a 18-dimensional object of a square^9)


  • Two rectangles, one horizontal 19:13 ratio the other vertical with a 7:13 ratio. Neither maps perfectly into the other with no gap left, but eventually they'll meet since they share the same 13 on one side.

    The analogy equivalent would be like numeric bases

    216 = 6^3 vs. 7,776 = 6^5

    -- meeting at (6 ^ 3) ^ 5 = 470,184,984,576 = (6 ^ 5) ^ 3 - the LCM point of their powers


  • A circle vs. a hexagon would be equivalent to bases, say, 61 vs. 181. They might get close, but since they simply don't share any prime bases at all, then no matter how many hexagons you have, you simply can’t fit every possible circle within them, and ditto for the reverse.

Then your question is equivalent to asking:

Why doesn't this circle completely fill a finite number of these trapezoids?

1

Unfortunately, there is no elegant way to perform arithmetic operations on float numbers without encountering such errors. This is because processors don't operate with decimal numbers; they use binary ones. Different processors may even work differently, leading to varied errors in calculations. To see what the number 0.2 actually looks like, you can run this code:

(0.2).toPrecision(50)
// 0.20000000000000001110223024625156540423631668090820

It's physically impossible for a computer's memory to store the exact number 0.2. JavaScript's job is to find a binary number that closely approximates 0.2 with a certain number of zeroes following it.

Similarly, there's no elegant way to round these numbers! Even standard JavaScript functions (like toFixed, toPrecision) can be inaccurate. This can vary depending on the computer, as different processors may yield different results.

(8.005).toPrecision(3) // 8.01
(1.005).toPrecision(3) // 1.00
(8.005).toFixed(2) // 8.01
(1.005).toFixed(2) // 1.00
Math.round((8.005) * 100) / 100 // 8.01
Math.round((1.005) * 100) / 100 // 1.00, surprise!

// This is the reason:
(8.005) * 100 = 800.5000000000001
(1.005) * 100 = 100.49999999999999

In my opinion, the simplest way to handle float numbers is to round them frequently, trimming off the accumulating errors from arithmetic operations. This allows us to continue using the standard Number type without complicating our program.

I believe the most reliable rounding method involves converting the number to a string and rounding manually by characters. A number derived from a string will convert back to the same string form, without changes. parseFloat('0.2').toString() === '0.2' This is crucial for eliminating errors, especially considering that all numeric constants in JavaScript code are text, as the entire code is text. JavaScript's compiler converts all numeric constants from the code into numbers just like parseFloat.

Based on these considerations, I wrote functions for correct rounding, based on conversion to and from a string, and optimized performance as much as possible. My solution has been thoroughly tested with different numbers (~130,000 test cases).

You can verify this in your browser console. If you have more elegant or efficient solutions, test them with my test. I would be happy to see such solutions.

My solution

const MAX_FLOAT_PRECISION = 15
const ROUND = 0
const FLOOR = 1
const CEIL = 2
const PRECISION = 0
const FRACTION = 1

function _round(value, digits, digitsType, roundType) {
  if (digitsType === PRECISION && digits <= 0) {
    throw new Error(`Precision digits (${digits}) must be > 0`)
  }
  if (digitsType === FRACTION && digits < 0) {
    throw new Error(`Fraction digits (${digits}) must be >= 0`)
  }
  if (!value) {
    return value
  }
  if ((digitsType === PRECISION && digits < MAX_FLOAT_PRECISION) ||
    digitsType === FRACTION) {
    value = fixFloat(value)
  }
  const negative = value < 0
  const valueAbs = negative ? -value : value
  const str = valueAbs.toExponential()
  const len = str.indexOf('e')
  let precisionDigits = digits
  let exponent
  if (digitsType === FRACTION) {
    exponent = parseInt(str.slice(len + 1))
    precisionDigits += exponent + 1
  }
  let index = precisionDigits > 0 ? precisionDigits + 1 : precisionDigits
  if (index >= len) {
    return value
  }
  let ch = index < 0 ? 0 : str.charCodeAt(index) - 48
  let increment
  switch (roundType) {
    case ROUND:
      increment =
        ch > 5 ||
          (!negative && ch === 5) ||
          (negative && ch === 5 && index < len - 1)
      break
    case FLOOR:
      increment = negative
      break
    case CEIL:
      increment = !negative
      break
  }
  if (precisionDigits <= 0) {
    if (increment) {
      if (typeof exponent === 'undefined') {
        exponent = parseInt(str.slice(len + 1))
      }
      return parseFloat(
        `${negative ? '-' : ''}1e${exponent - precisionDigits + 1}`,
      )
    }
    return negative ? -0 : 0
  }
  if (!increment) {
    return parseFloat(
      (negative ? '-' : '') +
        str.slice(0, index === 2 ? 1 : index) +
        str.slice(len),
    )
  }
  for (let nDigit = precisionDigits - 1; nDigit >= 0; nDigit--) {
    index = nDigit > 0 ? nDigit + 1 : nDigit
    ch = str.charCodeAt(index) - 48
    if (ch < 9) {
      return parseFloat(
        (negative ? '-' : '') + str.slice(0, index) + (ch + 1) + str.slice(len),
      )
    }
  }
  return parseFloat((negative ? '-' : '') + '10' + str.slice(len))
}

function roundPrecision(value, digits) {
  return _round(value, digits, PRECISION, ROUND)
}
function floorPrecision(value, digits) {
  return _round(value, digits, PRECISION, FLOOR)
}
function ceilPrecision(value, digits) {
  return _round(value, digits, PRECISION, CEIL)
}
function roundFraction(value, fractionDigits) {
  return _round(value, fractionDigits || 0, FRACTION, ROUND)
}
function floorFraction(value, fractionDigits) {
  return _round(value, fractionDigits || 0, FRACTION, FLOOR)
}
function ceilFraction(value, fractionDigits) {
  return _round(value, fractionDigits || 0, FRACTION, CEIL)
}
/**
 * @example 0.0000000000001 => 0
 * @example 0.9999999999999 => 1
 */
function fixFloat(value) {
  return roundPrecision(value, MAX_FLOAT_PRECISION)
}

Example of usage

console.log(roundPrecision(100500, 3)); // 101000
console.log(roundPrecision(100499.9, 3)); // 100000
console.log(floorPrecision(100999.9, 3)); // 100000
console.log(ceilPrecision(100000.1, 3)); // 101000
console.log(roundFraction(100.005, 2)); // 100.01
console.log(roundFraction(100.00499, 2)); // 100
console.log(floorFraction(100.00999, 2)); // 100
console.log(ceilFraction(100.00001, 2)); // 100.001

console.log(fixFloat(0.1 + 0.2) === 0.3); // true

Tests

function assertEqual(actual, expected) {
  if (actual !== expected) {
    throw new Error(`Assertion failed: expected ${expected}, got ${actual}`)
  }
}

function assertNotEqual(actual, expected) {
  if (actual === expected) {
    throw new Error(`Assertion failed: expected ${expected}, got ${actual}`)
  }
}

function testRound(func, input, expected) {
  const MIN_EPSILON = 1.1103e-16
  const MAX_EPSILON = 2.8486e-16
  if (input !== 0) {
    assertNotEqual(input - input * MIN_EPSILON, input)
  }
  assertEqual(fixFloat(input + input * MAX_EPSILON), input) // (-0) + (-0) = 0
  assertEqual(
    fixFloat(input - input * MAX_EPSILON),
    Object.is(input, -0) ? 0 : input,
  ) // (-0) - (-0) = 0
  assertEqual(func(input), expected)
  assertEqual(func(input + input * MAX_EPSILON), expected)
  assertEqual(
    func(input - input * MAX_EPSILON),
    Object.is(input, -0) ? 0 : expected,
  )
}

const test_roundPrecision = (input, precision, expected) => {
  testRound(o => roundPrecision(o, precision), input, expected)
}
const test_floorPrecision = (input, precision, expected) => {
  testRound(o => floorPrecision(o, precision), input, expected)
}
const test_ceilPrecision = (input, precision, expected) => {
  testRound(o => ceilPrecision(o, precision), input, expected)
}
const test_roundFraction = (input, fraction, expected) => {
  testRound(o => roundFraction(o, fraction), input, expected)
}
const test_floorFraction = (input, fraction, expected) => {
  testRound(o => floorFraction(o, fraction), input, expected)
}
const test_ceilFraction = (input, fraction, expected) => {
  testRound(o => ceilFraction(o, fraction), input, expected)
}

function test(name, func) {
  func()
  console.log(`✅ ${name}`)
}

test('roundPrecision', () => {
  assertEqual(Math.round(9.5), 10)
  assertEqual(Math.round(-9.5), -9)
  assertEqual(Math.round(9.499999999), 9)
  assertEqual(Math.round(-9.499999999), -9)
  assertEqual(Math.round(9.500000001), 10)
  assertEqual(Math.round(-9.500000001), -10)
  
  test_roundPrecision(0, 1, 0)
  test_roundPrecision(-0, 1, -0)
  test_roundPrecision(9, 1, 9)
  test_roundPrecision(-9, 1, -9)
  test_roundPrecision(9.5, 1, 10)
  test_roundPrecision(-9.5, 1, -9)
  test_roundPrecision(9.499999999, 1, 9)
  test_roundPrecision(-9.499999999, 1, -9)
  test_roundPrecision(9.999999999, 1, 10)
  test_roundPrecision(-9.999999999, 1, -10)
  test_roundPrecision(9.500000001, 1, 10)
  test_roundPrecision(-9.500000001, 1, -10)
  test_roundPrecision(9.0e-50, 1, 9.0e-50)
  test_roundPrecision(-9.0e-50, 1, -9.0e-50)
  test_roundPrecision(9.5e-50, 1, 1.0e-49)
  test_roundPrecision(-9.5e-50, 1, -9.0e-50)
  test_roundPrecision(9.499999999e-50, 1, 9.0e-50)
  test_roundPrecision(-9.499999999e-50, 1, -9.0e-50)
  test_roundPrecision(9.999999999e-50, 1, 1.0e-49)
  test_roundPrecision(-9.999999999e-50, 1, -1.0e-49)
  test_roundPrecision(9.500000001e-50, 1, 1.0e-49)
  test_roundPrecision(-9.500000001e-50, 1, -1.0e-49)
})

test('floorPrecision', () => {
  assertEqual(Math.floor(9.0), 9)
  assertEqual(Math.floor(-9.0), -9)
  assertEqual(Math.floor(9.0000001), 9)
  assertEqual(Math.floor(-9.0000001), -10)
  assertEqual(Math.floor(9.9999999), 9)
  assertEqual(Math.floor(-9.9999999), -10)
  
  test_floorPrecision(0, 1, 0)
  test_floorPrecision(-0, 1, -0)
  test_floorPrecision(9, 1, 9)
  test_floorPrecision(-9, 1, -9)
  test_floorPrecision(9.0, 1, 9)
  test_floorPrecision(-9.0, 1, -9)
  test_floorPrecision(9.0000001, 1, 9)
  test_floorPrecision(-9.0000001, 1, -10)
  test_floorPrecision(9.9999999, 1, 9)
  test_floorPrecision(-9.9999999, 1, -10)
  test_floorPrecision(9.0e-50, 1, 9.0e-50)
  test_floorPrecision(-9.0e-50, 1, -9.0e-50)
  test_floorPrecision(9.0e-50, 1, 9.0e-50)
  test_floorPrecision(-9.0e-50, 1, -9.0e-50)
  test_floorPrecision(9.0000001e-50, 1, 9.0e-50)
  test_floorPrecision(-9.0000001e-50, 1, -1.0e-49)
  test_floorPrecision(9.9999999e-50, 1, 9.0e-50)
  test_floorPrecision(-9.9999999e-50, 1, -1.0e-49)
})

test('ceilPrecision', () => {
  assertEqual(Math.ceil(9.0), 9)
  assertEqual(Math.ceil(-9.0), -9)
  assertEqual(Math.ceil(9.0000001), 10)
  assertEqual(Math.ceil(-9.0000001), -9)
  assertEqual(Math.ceil(9.9999999), 10)
  assertEqual(Math.ceil(-9.9999999), -9)
  
  test_ceilPrecision(0, 1, 0)
  test_ceilPrecision(-0, 1, -0)
  test_ceilPrecision(9, 1, 9)
  test_ceilPrecision(-9, 1, -9)
  test_ceilPrecision(9.0, 1, 9)
  test_ceilPrecision(-9.0, 1, -9)
  test_ceilPrecision(9.0000001, 1, 10)
  test_ceilPrecision(-9.0000001, 1, -9)
  test_ceilPrecision(9.9999999, 1, 10)
  test_ceilPrecision(-9.9999999, 1, -9)
  test_ceilPrecision(9.0e-50, 1, 9.0e-50)
  test_ceilPrecision(-9.0e-50, 1, -9.0e-50)
  test_ceilPrecision(9.0e-50, 1, 9.0e-50)
  test_ceilPrecision(-9.0e-50, 1, -9.0e-50)
  test_ceilPrecision(9.0000001e-50, 1, 1.0e-49)
  test_ceilPrecision(-9.0000001e-50, 1, -9.0e-50)
  test_ceilPrecision(9.9999999e-50, 1, 1.0e-49)
  test_ceilPrecision(-9.9999999e-50, 1, -9.0e-50)
})

test('roundFraction', () => {
  assertEqual(Math.round(-0), -0)
  assertEqual(Math.round(-0.1), -0)
  assertEqual(Math.round(9.5), 10)
  assertEqual(Math.round(-9.5), -9)
  assertEqual(Math.round(9.499999999), 9)
  assertEqual(Math.round(-9.499999999), -9)
  assertEqual(Math.round(9.500000001), 10)
  assertEqual(Math.round(-9.500000001), -10)
  
  test_roundFraction(0, 0, 0)
  test_roundFraction(-0, 0, -0)
  test_roundFraction(0.1, 0, 0)
  test_roundFraction(-0.1, 0, -0)
  test_roundFraction(9, 0, 9)
  test_roundFraction(-9, 0, -9)
  test_roundFraction(9.5, 0, 10)
  test_roundFraction(-9.5, 0, -9)
  test_roundFraction(9.499999999, 0, 9)
  test_roundFraction(-9.499999999, 0, -9)
  test_roundFraction(9.500000001, 0, 10)
  test_roundFraction(-9.500000001, 0, -10)
  test_roundFraction(0, 0, 0)
  test_roundFraction(-0, 0, -0)
  test_roundFraction(0.5, 0, 1)
  test_roundFraction(-0.5, 0, -0)
  test_roundFraction(0.499999999, 0, 0)
  test_roundFraction(-0.499999999, 0, -0)
  test_roundFraction(0.500000001, 0, 1)
  test_roundFraction(-0.500000001, 0, -1)
  test_roundFraction(0.09, 0, 0)
  test_roundFraction(-0.09, 0, -0)
  test_roundFraction(9.0e-10, 0, 0)
  test_roundFraction(-9.0e-10, 0, -0)
})

test('floorFraction', () => {
  assertEqual(Math.floor(-0), -0)
  assertEqual(Math.floor(-0.1), -1)
  assertEqual(Math.floor(9.5), 9)
  assertEqual(Math.floor(-9.5), -10)
  assertEqual(Math.floor(9.499999999), 9)
  assertEqual(Math.floor(-9.499999999), -10)
  assertEqual(Math.floor(9.500000001), 9)
  assertEqual(Math.floor(-9.500000001), -10)
  
  test_floorFraction(0, 0, 0)
  test_floorFraction(-0, 0, -0)
  test_floorFraction(0.1, 0, 0)
  test_floorFraction(-0.1, 0, -1)
  test_floorFraction(9, 0, 9)
  test_floorFraction(-9, 0, -9)
  test_floorFraction(9.5, 0, 9)
  test_floorFraction(-9.5, 0, -10)
  test_floorFraction(9.499999999, 0, 9)
  test_floorFraction(-9.499999999, 0, -10)
  test_floorFraction(9.500000001, 0, 9)
  test_floorFraction(-9.500000001, 0, -10)
  test_floorFraction(0.9, 0, 0)
  test_floorFraction(-0.9, 0, -1)
  test_floorFraction(9.0e-10, 0, 0)
  test_floorFraction(-9.0e-10, 0, -1)
})

test('ceilFraction', () => {
  assertEqual(Math.ceil(-0), -0)
  assertEqual(Math.ceil(-0.1), -0)
  assertEqual(Math.ceil(9.5), 10)
  assertEqual(Math.ceil(-9.5), -9)
  assertEqual(Math.ceil(9.499999999), 10)
  assertEqual(Math.ceil(-9.499999999), -9)
  assertEqual(Math.ceil(9.500000001), 10)
  assertEqual(Math.ceil(-9.500000001), -9)
  
  test_ceilFraction(0, 0, 0)
  test_ceilFraction(-0, 0, -0)
  test_ceilFraction(0.1, 0, 1)
  test_ceilFraction(-0.1, 0, -0)
  test_ceilFraction(9, 0, 9)
  test_ceilFraction(-9, 0, -9)
  test_ceilFraction(9.5, 0, 10)
  test_ceilFraction(-9.5, 0, -9)
  test_ceilFraction(9.499999999, 0, 10)
  test_ceilFraction(-9.499999999, 0, -9)
  test_ceilFraction(9.500000001, 0, 10)
  test_ceilFraction(-9.500000001, 0, -9)
  test_ceilFraction(0.09, 0, 1)
  test_ceilFraction(-0.09, 0, -0)
  test_ceilFraction(9.0e-10, 0, 1)
  test_ceilFraction(-9.0e-10, 0, -0)
})

test('extra', () => {
  assertEqual(fixFloat(49.34000000000001), 49.34)
  
  test_floorFraction(0.00000011111, 2, 0)
  test_floorFraction(0.011111, 2, 0.01)
  test_ceilFraction(0.0000001, 2, 0.01)
  test_ceilFraction(0.0100001, 2, 0.02)
  test_roundFraction(0.0000001, 2, 0)
  test_roundFraction(0.0049999, 2, 0)
  test_roundFraction(0.005, 2, 0.01)
  test_roundFraction(0.0149999, 2, 0.01)
  test_roundFraction(0.015, 2, 0.02)
  test_floorFraction(111 * 1.18, 2, 130.98)
  test_roundPrecision(111, 1, 100)
  test_roundPrecision(111, 2, 110)
  test_roundPrecision(0.1, 1, 0.1)
  test_roundPrecision(0.01, 1, 0.01)
  test_roundPrecision(0.999, 2, 1)
  test_roundPrecision(9.05e-97, 2, 9.1e-97)
  test_roundPrecision(0.01 * 1.01 - 0.01, 13, 0.0001)
  test_roundPrecision(1.05e-200, 5, 1.05e-200)
  test_roundPrecision(1.05e-50, 5, 1.05e-50)
})

This answer was intended for a JavaScript question, but it has been closed, marked as a duplicate, and redirected here. But most likely my answer will be suitable for many other languages, since the logic of working with float is approximately the same everywhere.

-1

In decimal, 1/3 cannot be represented exactly with a finite number of digits.

E.g. 1/3 ~ 0.33333333 and 3 x (1/3) ~ 0.99999999 != 1.

Likewise, in binary 1/5 cannot be represented exactly with a finite number of bits.

E.g. 1/5 ~ 0.00110011b and 101b x 0.00110011b = 0.11111111 != 1.

1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.