Programming Search⌘K

Taskcore

Compare floating-point numbers

Also called compare floats, float equality, approximately equal, isclose, almost equal, epsilon comparison, ULP distance, NaN comparison.

Tell whether two floats are close, with a relative and an absolute tolerance, and not with ==. Count the floats between them with the ULP distance, and treat NaN apart.

Task

Tell whether two floats a and b are close enough to be the same value.

A float is often not exact. The Python tutorial says that "summing three values of 0.1 may not yield exactly 0.3, either"1, so 0.1 + 0.2 == 0.3 is false in each language that uses binary floats. Thus a test with == is almost never the correct test for computed floats. Use a tolerance.

The function is_close(a, b, rel_tol, abs_tol) returns true when

a == b  or  |a - b| <= max(rel_tol * max(|a|, |b|), abs_tol)

This is the rule of math.isclose in Python2. It has two tolerances:

  • The relative tolerance rel_tol scales with the size of the values. With rel_tol = 1e-9, the values must agree to about 9 decimal digits, both for 1.0 and for 1e10.
  • The absolute tolerance abs_tol is a fixed distance. It is necessary near zero, because "no value is small relative to zero"3.

The test uses the larger of |a| and |b|, so is_close(a, b) is always the same as is_close(b, a).

The special values follow rules of their own: NaN is close to no value, NaN included, and an infinity is close only to itself. JSON cannot hold these values, so the cases of the contract have finite values only, and the native tests check NaN and the infinities.

Solutions

Language Tolerance test Machine epsilon and ULP
Python math.isclose(a, b, rel_tol=..., abs_tol=...) math.ulp(x), math.nextafter(x, y), sys.float_info.epsilon
JavaScript, TypeScript own function Number.EPSILON
Java own function Math.ulp(x), Math.nextUp(x)
C, C++ own function DBL_EPSILON, nextafter(x, y)
C# own function double.Epsilon is not the machine epsilon
Go own function math.Nextafter(x, y), math.Float64bits(x)
Rust own function f64::EPSILON, x.to_bits()
Bash awk none
  • Python. math.isclose "Return True if the values a and b are close to each other and False otherwise"2. Its result is abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)2, and the defaults are rel_tol=1e-09 and abs_tol=0.02. The tutorial says that "the math.isclose() function can be useful for comparing inexact values"1. The design is in PEP 485: "NaN is not considered close to any other value, including NaN"3, and "inf and -inf are only considered close to themselves"3.
  • JavaScript. There is no built-in function. The solution tests a === b first, which is true for two equal infinities. Then Number.isFinite sends NaN and the infinities to false. Number.EPSILON is "the difference between 1 and the smallest floating point number greater than 1"4; it is a good tolerance only for values near 1.
  • TypeScript. The same code as JavaScript.
  • Java. The same function, with Double.isFinite. Math.ulp "Returns the size of an ulp of the argument"5, and Math.nextUp "Returns the floating-point value adjacent to d in the direction of positive infinity"5.
  • C, C++. The same function, with isfinite, fabs and fmax. DBL_EPSILON is the "difference between 1.0 and the next representable value"6 for double. nextafter(from, to) "returns the next representable value of from in the direction of to"7.
  • C#. The same function, with double.IsFinite. Do not use double.Epsilon as a tolerance: it "Represents the smallest positive Double value that is greater than zero"8.
  • Go. The same function, with math.IsInf and math.IsNaN. "Nextafter returns the next representable float64 value after x towards y"9, and math.Float64bits "returns the IEEE 754 binary representation of f"9.
  • Rust. The same function, with f64::is_finite. f64::EPSILON is the "Machine epsilon value for f64"10, and to_bits is a "Raw transmutation to u64"10.
  • Bash. Shell arithmetic "is done in the largest fixed-width integers available"11, so there are no floats. The solution gives the numbers to awk, where "All arithmetic shall follow the semantics of floating-point arithmetic as specified by the ISO C standard"12.

The problem and the fix in Python:

import math

x = 0.1 + 0.2
print(x, x == 0.3, math.isclose(x, 0.3))
print(math.isclose(1e-12, 0.0), math.isclose(1e-12, 0.0, abs_tol=1e-9))
print(math.ulp(1.0), math.ulp(1e16), math.nextafter(1.0, 2.0))
Output
0.30000000000000004 False True
False True
2.220446049250313e-16 2.0 1.0000000000000002

The space between two floats grows with their size: math.ulp(1e16) is 2.0. So a fixed tolerance that is right near 1 is too small for large values, and too large for small values.

The ULP distance

Another test counts the floats between a and b. This count is the distance in units in the last place (ULP). For two finite floats of the same sign, the bit patterns, read as integers, are in the same order as the floats. The distance is the difference of the integers. A negative float needs a mapping first, so that -0.0 and 0.0 give the same integer:

package main

import (
	"fmt"
	"math"
)

// ordered maps the bits of a finite float to an integer in the order of the floats.
func ordered(x float64) int64 {
	b := int64(math.Float64bits(x))
	if b < 0 {
		return -(b & math.MaxInt64)
	}
	return b
}

func ulpDistance(a, b float64) int64 {
	d := ordered(a) - ordered(b)
	if d < 0 {
		return -d
	}
	return d
}

func main() {
	x, y := 0.1, 0.2
	fmt.Println(ulpDistance(x+y, 0.3))
	fmt.Println(ulpDistance(1, math.Nextafter(1, 2)))
	fmt.Println(ulpDistance(math.Copysign(0, -1), 0))
	fmt.Println(ulpDistance(-math.SmallestNonzeroFloat64, math.SmallestNonzeroFloat64))
}
Output
1
1
0
2

A test such as "at most 4 ULP apart" works at each size, but not near zero: the two smallest floats of opposite signs are 2 ULP apart, while 1e-300 and 0.0 are far apart in ULP. So the ULP test also needs an absolute tolerance near zero.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. Each native test also checks each case with a and b swapped.

  • zero-and-zero: equal values are close, also with both tolerances 0.
  • one-ulp-apart: with both tolerances 0, only equal values are close.
  • near-zero-relative, near-zero-absolute: 1e-12 is not close to 0.0 with a relative tolerance only. It is close with abs_tol = 1e-9.
  • opposite-signs, opposite-signs-absolute: 1e-10 and -1e-10 are close only with an absolute tolerance.
  • on-the-boundary, swapped-boundary, past-the-boundary: with rel_tol = 0.1, 9.0 is close to 10.0 in both orders, and 8.875 is not.
  • negative-values: the absolute values set the tolerance.
  • NaN and the infinities, in the native tests only: is_close(NaN, NaN) is false, is_close(inf, inf) is true, and is_close(inf, 1e308) is false.

Pitfalls

  • == on computed floats. 0.1 + 0.2 == 0.3 is false (see the Python block). Compare computed floats with a tolerance. Use == only when the value is exact, for example a value that the program stored and reads back.

  • A fixed epsilon. Math.abs(a - b) < Number.EPSILON works for values near 1, but not for large values. The sum 1000.1 + 1000.2 is a few ULP from 2000.3, and the difference is larger than Number.EPSILON:

This code runs but gives a wrong answer on purpose.

const closeFixed = (a, b) => Math.abs(a - b) < Number.EPSILON;
console.log(closeFixed(0.1 + 0.2, 0.3), closeFixed(1000.1 + 1000.2, 2000.3));
console.log(1000.1 + 1000.2, Math.abs(1000.1 + 1000.2 - 2000.3));
Output
true false
2000.3000000000002 2.2737367544323206e-13
  • double.Epsilon in C#. The .NET documentation says that "The value of the Epsilon property is not equivalent to machine epsilon"8. It is about 4.9e-324, so a test Math.Abs(a - b) < double.Epsilon is the same as a == b.

  • A relative tolerance near zero. The Python manual says that isclose(x, 0) "is False for any nonzero x and rel_tol less than 1.0"2. When one of the values can be 0, give an absolute tolerance too.

  • An asymmetric test. A test such as |a - b| <= rel_tol * |b| uses only one of the values. PEP 485 calls it asymmetric: then "isclose(a,b) is not necessarily the same as isclose(b,a)"3. With rel_tol = 0.1, the asymmetric test says that 10.0 is close to 9.0, and that 9.0 is not close to 10.0.

  • NaN. "When NaN is one of the operands of any relational comparison"13, the result is false, and NaN is unequal to each value, also to NaN13. So x == x is false when x is NaN, and a sort or a search with < gives wrong results when the data has a NaN. Test for NaN with math.isnan, Number.isNaN, Double.isNaN or isnan.

  • An infinity. Without the first test a == b, the difference inf - inf is NaN, so two equal infinities are not close. Without the test of isfinite, |inf - 1e308| is infinite, and the relative tolerance rel_tol * inf is infinite too, so infinity is close to 1e308.

See also the concepts Floating-point arithmetic, Floating-point rounding error, Machine epsilon and ULP, NaN and infinity and IEEE 754.

Code

The build runs the native tests of each language in a pinned toolchain.

is_close.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compare-floating-point-numbers/.
import math


def is_close(a: float, b: float, rel_tol: float, abs_tol: float) -> bool:
    """Tells whether a and b are close: a relative tolerance for large values,
    an absolute tolerance near zero. NaN is close to no value, and an
    infinity is close only to itself."""
    return math.isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol)
test_is_close.py 46 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compare-floating-point-numbers/.
import math

import pytest

from is_close import is_close

CASES = {
    "equal": (1.5, 1.5, 1e-9, 0.0, True),
    "sum-of-tenths": (0.30000000000000004, 0.3, 1e-9, 0.0, True),
    "different": (1.0, 1.1, 1e-9, 0.0, False),
    "large-values": (10000000000.0, 10000000001.0, 1e-9, 0.0, True),
    "zero-and-zero": (0.0, 0.0, 0.0, 0.0, True),
    "one-ulp-apart": (1.0, 1.0000000000000002, 0.0, 0.0, False),
    "near-zero-relative": (1e-12, 0.0, 1e-9, 0.0, False),
    "near-zero-absolute": (1e-12, 0.0, 1e-9, 1e-9, True),
    "opposite-signs": (1e-10, -1e-10, 1e-9, 0.0, False),
    "opposite-signs-absolute": (1e-10, -1e-10, 1e-9, 1e-9, True),
    "on-the-boundary": (10.0, 9.0, 0.1, 0.0, True),
    "swapped-boundary": (9.0, 10.0, 0.1, 0.0, True),
    "past-the-boundary": (10.0, 8.875, 0.1, 0.0, False),
    "negative-values": (-1.0, -1.0000000001, 1e-9, 0.0, True),
}


@pytest.mark.parametrize("case", CASES)
def test_is_close(case):
    a, b, rel_tol, abs_tol, want = CASES[case]
    assert is_close(a, b, rel_tol, abs_tol) is want
    assert is_close(b, a, rel_tol, abs_tol) is want


def test_non_finite():
    nan, inf = math.nan, math.inf
    assert not is_close(nan, nan, 1e-9, 0.0)
    assert not is_close(nan, 1.0, 1e-9, 1.0)
    assert is_close(inf, inf, 1e-9, 0.0)
    assert not is_close(inf, -inf, 1e-9, 0.0)
    assert not is_close(inf, 1e308, 1e-9, 0.0)


def test_equality_and_ulp():
    assert 0.1 + 0.2 != 0.3
    assert math.nextafter(1.0, 2.0) == 1.0000000000000002
    assert math.ulp(1.0) == 2.0**-52
is_close.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.

#pragma once

#include <algorithm>
#include <cmath>

// Tells whether a and b are close: |a - b| <= max(rel_tol * max(|a|, |b|), abs_tol).
// NaN is close to no value, and an infinity is close only to itself.
inline bool is_close(double a, double b, double rel_tol, double abs_tol) {
    if (a == b) {
        return true;  // also an infinity and itself
    }
    if (!std::isfinite(a) || !std::isfinite(b)) {
        return false;  // NaN or an infinity
    }
    const double diff = std::fabs(a - b);
    return diff <= std::max(rel_tol * std::max(std::fabs(a), std::fabs(b)), abs_tol);
}
test_is_close.cpp 62 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.

#include "is_close.hpp"

#include <cmath>
#include <cstdio>
#include <limits>

namespace {

struct TestCase {
    const char *name;
    double a, b, rel_tol, abs_tol;
    bool want;
};

const TestCase cases[] = {
    {"equal", 1.5, 1.5, 1e-9, 0.0, true},
    {"sum-of-tenths", 0.30000000000000004, 0.3, 1e-9, 0.0, true},
    {"different", 1.0, 1.1, 1e-9, 0.0, false},
    {"large-values", 10000000000.0, 10000000001.0, 1e-9, 0.0, true},
    {"zero-and-zero", 0.0, 0.0, 0.0, 0.0, true},
    {"one-ulp-apart", 1.0, 1.0000000000000002, 0.0, 0.0, false},
    {"near-zero-relative", 1e-12, 0.0, 1e-9, 0.0, false},
    {"near-zero-absolute", 1e-12, 0.0, 1e-9, 1e-9, true},
    {"opposite-signs", 1e-10, -1e-10, 1e-9, 0.0, false},
    {"opposite-signs-absolute", 1e-10, -1e-10, 1e-9, 1e-9, true},
    {"on-the-boundary", 10.0, 9.0, 0.1, 0.0, true},
    {"swapped-boundary", 9.0, 10.0, 0.1, 0.0, true},
    {"past-the-boundary", 10.0, 8.875, 0.1, 0.0, false},
    {"negative-values", -1.0, -1.0000000001, 1e-9, 0.0, true},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto &c : cases) {
        if (is_close(c.a, c.b, c.rel_tol, c.abs_tol) != c.want ||
            is_close(c.b, c.a, c.rel_tol, c.abs_tol) != c.want) {
            std::fprintf(stderr, "case %s failed\n", c.name);
            ++failures;
        }
    }
    constexpr double nan = std::numeric_limits<double>::quiet_NaN();
    constexpr double inf = std::numeric_limits<double>::infinity();
    if (is_close(nan, nan, 1e-9, 0.0) || !is_close(inf, inf, 1e-9, 0.0) ||
        is_close(inf, -inf, 1e-9, 0.0) || is_close(inf, 1e308, 1e-9, 0.0)) {
        std::fprintf(stderr, "non-finite values failed\n");
        ++failures;
    }
    if (std::nextafter(1.0, 2.0) - 1.0 != std::numeric_limits<double>::epsilon()) {
        std::fprintf(stderr, "epsilon failed\n");
        ++failures;
    }
    if (failures != 0) {
        return 1;
    }
    std::puts("ok");
    return 0;
}
IsClose.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.

final class IsClose {
  private IsClose() {}

  /**
   * Tells whether a and b are close, by the rule of math.isclose in Python: |a - b| <= max(relTol *
   * max(|a|, |b|), absTol). NaN is close to no value, and an infinity is close only to itself.
   */
  static boolean isClose(double a, double b, double relTol, double absTol) {
    if (a == b) {
      return true; // also an infinity and itself
    }
    if (!Double.isFinite(a) || !Double.isFinite(b)) {
      return false; // NaN or an infinity
    }
    double diff = Math.abs(a - b);
    return diff <= Math.max(relTol * Math.max(Math.abs(a), Math.abs(b)), absTol);
  }
}
IsCloseTest.java 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class IsCloseTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("equal", 1.5, 1.5, 1e-9, 0.0, true),
        Arguments.of("sum-of-tenths", 0.30000000000000004, 0.3, 1e-9, 0.0, true),
        Arguments.of("different", 1.0, 1.1, 1e-9, 0.0, false),
        Arguments.of("large-values", 10000000000.0, 10000000001.0, 1e-9, 0.0, true),
        Arguments.of("zero-and-zero", 0.0, 0.0, 0.0, 0.0, true),
        Arguments.of("one-ulp-apart", 1.0, 1.0000000000000002, 0.0, 0.0, false),
        Arguments.of("near-zero-relative", 1e-12, 0.0, 1e-9, 0.0, false),
        Arguments.of("near-zero-absolute", 1e-12, 0.0, 1e-9, 1e-9, true),
        Arguments.of("opposite-signs", 1e-10, -1e-10, 1e-9, 0.0, false),
        Arguments.of("opposite-signs-absolute", 1e-10, -1e-10, 1e-9, 1e-9, true),
        Arguments.of("on-the-boundary", 10.0, 9.0, 0.1, 0.0, true),
        Arguments.of("swapped-boundary", 9.0, 10.0, 0.1, 0.0, true),
        Arguments.of("past-the-boundary", 10.0, 8.875, 0.1, 0.0, false),
        Arguments.of("negative-values", -1.0, -1.0000000001, 1e-9, 0.0, true));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void check(String name, double a, double b, double relTol, double absTol, boolean want) {
    assertEquals(want, IsClose.isClose(a, b, relTol, absTol), name);
    assertEquals(want, IsClose.isClose(b, a, relTol, absTol), name);
  }

  @Test
  void nonFinite() {
    assertFalse(IsClose.isClose(Double.NaN, Double.NaN, 1e-9, 0.0));
    assertTrue(IsClose.isClose(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 1e-9, 0.0));
    assertFalse(IsClose.isClose(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1e-9, 0.0));
    assertFalse(IsClose.isClose(Double.POSITIVE_INFINITY, 1e308, 1e-9, 0.0));
  }

  @Test
  void equalityAndUlp() {
    assertNotEquals(0.3, 0.1 + 0.2);
    assertEquals(Math.ulp(1.0), Math.nextUp(1.0) - 1.0);
  }
}
is_close.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.

#include "is_close.h"

#include <math.h>

bool is_close(double a, double b, double rel_tol, double abs_tol) {
    if (a == b) {
        return true; // also an infinity and itself
    }
    if (!isfinite(a) || !isfinite(b)) {
        return false; // NaN or an infinity
    }
    double diff = fabs(a - b);
    return diff <= fmax(rel_tol * fmax(fabs(a), fabs(b)), abs_tol);
}
is_close.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.

#ifndef IS_CLOSE_H
#define IS_CLOSE_H

#include <stdbool.h>

// Tells whether a and b are close: |a - b| <= max(rel_tol * max(|a|, |b|), abs_tol).
// NaN is close to no value, and an infinity is close only to itself.
bool is_close(double a, double b, double rel_tol, double abs_tol);

#endif
test_is_close.c 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.

#include "is_close.h"

#include <float.h>
#include <math.h>
#include <stdio.h>

struct test_case {
    const char *name;
    double a, b, rel_tol, abs_tol;
    bool want;
};

static const struct test_case cases[] = {
    {"equal", 1.5, 1.5, 1e-9, 0.0, true},
    {"sum-of-tenths", 0.30000000000000004, 0.3, 1e-9, 0.0, true},
    {"different", 1.0, 1.1, 1e-9, 0.0, false},
    {"large-values", 10000000000.0, 10000000001.0, 1e-9, 0.0, true},
    {"zero-and-zero", 0.0, 0.0, 0.0, 0.0, true},
    {"one-ulp-apart", 1.0, 1.0000000000000002, 0.0, 0.0, false},
    {"near-zero-relative", 1e-12, 0.0, 1e-9, 0.0, false},
    {"near-zero-absolute", 1e-12, 0.0, 1e-9, 1e-9, true},
    {"opposite-signs", 1e-10, -1e-10, 1e-9, 0.0, false},
    {"opposite-signs-absolute", 1e-10, -1e-10, 1e-9, 1e-9, true},
    {"on-the-boundary", 10.0, 9.0, 0.1, 0.0, true},
    {"swapped-boundary", 9.0, 10.0, 0.1, 0.0, true},
    {"past-the-boundary", 10.0, 8.875, 0.1, 0.0, false},
    {"negative-values", -1.0, -1.0000000001, 1e-9, 0.0, true},
};

int main(void) {
    int failures = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        if (is_close(c->a, c->b, c->rel_tol, c->abs_tol) != c->want ||
            is_close(c->b, c->a, c->rel_tol, c->abs_tol) != c->want) {
            fprintf(stderr, "case %s failed\n", c->name);
            failures++;
        }
    }
    if (is_close(NAN, NAN, 1e-9, 0.0) || !is_close(INFINITY, INFINITY, 1e-9, 0.0) ||
        is_close(INFINITY, -INFINITY, 1e-9, 0.0) || is_close(INFINITY, 1e308, 1e-9, 0.0)) {
        fprintf(stderr, "non-finite values failed\n");
        failures++;
    }
    if (nextafter(1.0, 2.0) - 1.0 != DBL_EPSILON) {
        fprintf(stderr, "DBL_EPSILON failed\n");
        failures++;
    }
    if (failures != 0) {
        return 1;
    }
    puts("ok");
    return 0;
}
IsClose.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.
using System;

public static class FloatCompare
{
    // Tells whether a and b are close: |a - b| <= max(relTol * max(|a|, |b|), absTol).
    // NaN is close to no value, and an infinity is close only to itself.
    public static bool IsClose(double a, double b, double relTol, double absTol)
    {
        if (a == b)
        {
            return true; // also an infinity and itself
        }
        if (!double.IsFinite(a) || !double.IsFinite(b))
        {
            return false; // NaN or an infinity
        }
        double diff = Math.Abs(a - b);
        return diff <= Math.Max(relTol * Math.Max(Math.Abs(a), Math.Abs(b)), absTol);
    }
}
IsCloseTests.cs 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.
using System;
using Xunit;

public sealed class IsCloseTests
{
    public static TheoryData<string, double, double, double, double, bool> Cases => new()
    {
        { "equal", 1.5, 1.5, 1e-9, 0.0, true },
        { "sum-of-tenths", 0.30000000000000004, 0.3, 1e-9, 0.0, true },
        { "different", 1.0, 1.1, 1e-9, 0.0, false },
        { "large-values", 10000000000.0, 10000000001.0, 1e-9, 0.0, true },
        { "zero-and-zero", 0.0, 0.0, 0.0, 0.0, true },
        { "one-ulp-apart", 1.0, 1.0000000000000002, 0.0, 0.0, false },
        { "near-zero-relative", 1e-12, 0.0, 1e-9, 0.0, false },
        { "near-zero-absolute", 1e-12, 0.0, 1e-9, 1e-9, true },
        { "opposite-signs", 1e-10, -1e-10, 1e-9, 0.0, false },
        { "opposite-signs-absolute", 1e-10, -1e-10, 1e-9, 1e-9, true },
        { "on-the-boundary", 10.0, 9.0, 0.1, 0.0, true },
        { "swapped-boundary", 9.0, 10.0, 0.1, 0.0, true },
        { "past-the-boundary", 10.0, 8.875, 0.1, 0.0, false },
        { "negative-values", -1.0, -1.0000000001, 1e-9, 0.0, true },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, double a, double b, double relTol, double absTol, bool want)
    {
        Assert.True(want == FloatCompare.IsClose(a, b, relTol, absTol), name);
        Assert.True(want == FloatCompare.IsClose(b, a, relTol, absTol), name);
    }

    [Fact]
    public void NonFinite()
    {
        Assert.False(FloatCompare.IsClose(double.NaN, double.NaN, 1e-9, 0.0));
        Assert.True(FloatCompare.IsClose(double.PositiveInfinity, double.PositiveInfinity, 1e-9, 0.0));
        Assert.False(FloatCompare.IsClose(double.PositiveInfinity, double.NegativeInfinity, 1e-9, 0.0));
        Assert.False(FloatCompare.IsClose(double.PositiveInfinity, 1e308, 1e-9, 0.0));
    }

    [Fact]
    public void DoubleEpsilonIsNotMachineEpsilon()
    {
        Assert.True(double.Epsilon < 1e-300);
        Assert.False(Math.Abs(0.1 + 0.2 - 0.3) < double.Epsilon);
    }
}
is_close.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.

/**
 * Tells whether a and b are close, by the rule of math.isclose in Python:
 * |a - b| <= max(relTol * max(|a|, |b|), absTol). NaN is close to no value,
 * and an infinity is close only to itself.
 * @param {number} a
 * @param {number} b
 * @param {number} relTol
 * @param {number} absTol
 * @returns {boolean}
 */
export function isClose(a, b, relTol, absTol) {
  if (a === b) return true; // also Infinity === Infinity
  if (!Number.isFinite(a) || !Number.isFinite(b)) return false; // NaN or an infinity
  const diff = Math.abs(a - b);
  return diff <= Math.max(relTol * Math.max(Math.abs(a), Math.abs(b)), absTol);
}
is_close.test.js 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.
import assert from "node:assert/strict";
import { test } from "node:test";

import { isClose } from "./is_close.js";

const cases = [
  ["equal", 1.5, 1.5, 1e-9, 0.0, true],
  ["sum-of-tenths", 0.30000000000000004, 0.3, 1e-9, 0.0, true],
  ["different", 1.0, 1.1, 1e-9, 0.0, false],
  ["large-values", 10000000000.0, 10000000001.0, 1e-9, 0.0, true],
  ["zero-and-zero", 0.0, 0.0, 0.0, 0.0, true],
  ["one-ulp-apart", 1.0, 1.0000000000000002, 0.0, 0.0, false],
  ["near-zero-relative", 1e-12, 0.0, 1e-9, 0.0, false],
  ["near-zero-absolute", 1e-12, 0.0, 1e-9, 1e-9, true],
  ["opposite-signs", 1e-10, -1e-10, 1e-9, 0.0, false],
  ["opposite-signs-absolute", 1e-10, -1e-10, 1e-9, 1e-9, true],
  ["on-the-boundary", 10.0, 9.0, 0.1, 0.0, true],
  ["swapped-boundary", 9.0, 10.0, 0.1, 0.0, true],
  ["past-the-boundary", 10.0, 8.875, 0.1, 0.0, false],
  ["negative-values", -1.0, -1.0000000001, 1e-9, 0.0, true],
];

for (const [name, a, b, relTol, absTol, want] of cases) {
  test(name, () => {
    assert.equal(isClose(a, b, relTol, absTol), want);
    assert.equal(isClose(b, a, relTol, absTol), want);
  });
}

test("NaN and infinities", () => {
  assert.equal(isClose(NaN, NaN, 1e-9, 0), false);
  assert.equal(isClose(Infinity, Infinity, 1e-9, 0), true);
  assert.equal(isClose(Infinity, -Infinity, 1e-9, 0), false);
  assert.equal(isClose(Infinity, 1e308, 1e-9, 0), false);
});

test("equality and Number.EPSILON", () => {
  assert.notEqual(0.1 + 0.2, 0.3);
  assert.equal(1 + Number.EPSILON, 1.0000000000000002);
});
is_close.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.

// Tells whether a and b are close, by the rule of math.isclose in Python:
// |a - b| <= max(relTol * max(|a|, |b|), absTol). NaN is close to no value,
// and an infinity is close only to itself.
export function isClose(a: number, b: number, relTol: number, absTol: number): boolean {
  if (a === b) return true; // also Infinity === Infinity
  if (!Number.isFinite(a) || !Number.isFinite(b)) return false; // NaN or an infinity
  const diff = Math.abs(a - b);
  return diff <= Math.max(relTol * Math.max(Math.abs(a), Math.abs(b)), absTol);
}
is_close.test.ts 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.
import assert from "node:assert/strict";
import { test } from "node:test";

import { isClose } from "./is_close.ts";

const cases: [string, number, number, number, number, boolean][] = [
  ["equal", 1.5, 1.5, 1e-9, 0.0, true],
  ["sum-of-tenths", 0.30000000000000004, 0.3, 1e-9, 0.0, true],
  ["different", 1.0, 1.1, 1e-9, 0.0, false],
  ["large-values", 10000000000.0, 10000000001.0, 1e-9, 0.0, true],
  ["zero-and-zero", 0.0, 0.0, 0.0, 0.0, true],
  ["one-ulp-apart", 1.0, 1.0000000000000002, 0.0, 0.0, false],
  ["near-zero-relative", 1e-12, 0.0, 1e-9, 0.0, false],
  ["near-zero-absolute", 1e-12, 0.0, 1e-9, 1e-9, true],
  ["opposite-signs", 1e-10, -1e-10, 1e-9, 0.0, false],
  ["opposite-signs-absolute", 1e-10, -1e-10, 1e-9, 1e-9, true],
  ["on-the-boundary", 10.0, 9.0, 0.1, 0.0, true],
  ["swapped-boundary", 9.0, 10.0, 0.1, 0.0, true],
  ["past-the-boundary", 10.0, 8.875, 0.1, 0.0, false],
  ["negative-values", -1.0, -1.0000000001, 1e-9, 0.0, true],
];

for (const [name, a, b, relTol, absTol, want] of cases) {
  test(name, () => {
    assert.equal(isClose(a, b, relTol, absTol), want);
    assert.equal(isClose(b, a, relTol, absTol), want);
  });
}

test("NaN and infinities", () => {
  assert.equal(isClose(NaN, NaN, 1e-9, 0), false);
  assert.equal(isClose(Infinity, Infinity, 1e-9, 0), true);
  assert.equal(isClose(Infinity, -Infinity, 1e-9, 0), false);
  assert.equal(isClose(Infinity, 1e308, 1e-9, 0), false);
});

test("equality and Number.EPSILON", () => {
  assert.notEqual(0.1 + 0.2, 0.3);
  assert.equal(1 + Number.EPSILON, 1.0000000000000002);
});
is_close.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.

// Package floatcmp compares floats with a tolerance.
package floatcmp

import "math"

// IsClose tells whether a and b are close:
// |a - b| <= max(relTol * max(|a|, |b|), absTol).
// NaN is close to no value, and an infinity is close only to itself.
func IsClose(a, b, relTol, absTol float64) bool {
	if a == b {
		return true // also an infinity and itself
	}
	if math.IsInf(a, 0) || math.IsInf(b, 0) || math.IsNaN(a) || math.IsNaN(b) {
		return false
	}
	diff := math.Abs(a - b)
	return diff <= math.Max(relTol*math.Max(math.Abs(a), math.Abs(b)), absTol)
}
is_close_test.go 60 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.

package floatcmp

import (
	"math"
	"testing"
)

var cases = []struct {
	name                 string
	a, b, relTol, absTol float64
	want                 bool
}{
	{"equal", 1.5, 1.5, 1e-9, 0.0, true},
	{"sum-of-tenths", 0.30000000000000004, 0.3, 1e-9, 0.0, true},
	{"different", 1.0, 1.1, 1e-9, 0.0, false},
	{"large-values", 10000000000.0, 10000000001.0, 1e-9, 0.0, true},
	{"zero-and-zero", 0.0, 0.0, 0.0, 0.0, true},
	{"one-ulp-apart", 1.0, 1.0000000000000002, 0.0, 0.0, false},
	{"near-zero-relative", 1e-12, 0.0, 1e-9, 0.0, false},
	{"near-zero-absolute", 1e-12, 0.0, 1e-9, 1e-9, true},
	{"opposite-signs", 1e-10, -1e-10, 1e-9, 0.0, false},
	{"opposite-signs-absolute", 1e-10, -1e-10, 1e-9, 1e-9, true},
	{"on-the-boundary", 10.0, 9.0, 0.1, 0.0, true},
	{"swapped-boundary", 9.0, 10.0, 0.1, 0.0, true},
	{"past-the-boundary", 10.0, 8.875, 0.1, 0.0, false},
	{"negative-values", -1.0, -1.0000000001, 1e-9, 0.0, true},
}

func TestIsClose(t *testing.T) {
	for _, c := range cases {
		if got := IsClose(c.a, c.b, c.relTol, c.absTol); got != c.want {
			t.Errorf("%s: got %v", c.name, got)
		}
		if got := IsClose(c.b, c.a, c.relTol, c.absTol); got != c.want {
			t.Errorf("%s swapped: got %v", c.name, got)
		}
	}
}

func TestNonFinite(t *testing.T) {
	nan, inf := math.NaN(), math.Inf(1)
	if IsClose(nan, nan, 1e-9, 0) || !IsClose(inf, inf, 1e-9, 0) ||
		IsClose(inf, -inf, 1e-9, 0) || IsClose(inf, 1e308, 1e-9, 0) {
		t.Error("non-finite values")
	}
}

func TestSumOfTenths(t *testing.T) {
	// The variables make the sum a float64 sum; a sum of two constants is exact.
	x, y := 0.1, 0.2
	if x+y == 0.3 {
		t.Error("0.1 + 0.2 == 0.3")
	}
	if math.Nextafter(1, 2)-1 != 0x1p-52 {
		t.Error("Nextafter")
	}
}
is_close.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.

/// Tells whether `a` and `b` are close:
/// |a - b| <= max(rel_tol * max(|a|, |b|), abs_tol).
/// NaN is close to no value, and an infinity is close only to itself.
pub fn is_close(a: f64, b: f64, rel_tol: f64, abs_tol: f64) -> bool {
    if a == b {
        return true; // also an infinity and itself
    }
    if !a.is_finite() || !b.is_finite() {
        return false; // NaN or an infinity
    }
    let diff = (a - b).abs();
    diff <= (rel_tol * a.abs().max(b.abs())).max(abs_tol)
}
tests/is_close_test.rs 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compare-floating-point-numbers/.

use algo_compare_floating_point_numbers::is_close;

#[test]
fn cases() {
    let cases: Vec<(&str, f64, f64, f64, f64, bool)> = vec![
        ("equal", 1.5, 1.5, 1e-9, 0.0, true),
        ("sum-of-tenths", 0.30000000000000004, 0.3, 1e-9, 0.0, true),
        ("different", 1.0, 1.1, 1e-9, 0.0, false),
        ("large-values", 10000000000.0, 10000000001.0, 1e-9, 0.0, true),
        ("zero-and-zero", 0.0, 0.0, 0.0, 0.0, true),
        ("one-ulp-apart", 1.0, 1.0000000000000002, 0.0, 0.0, false),
        ("near-zero-relative", 1e-12, 0.0, 1e-9, 0.0, false),
        ("near-zero-absolute", 1e-12, 0.0, 1e-9, 1e-9, true),
        ("opposite-signs", 1e-10, -1e-10, 1e-9, 0.0, false),
        ("opposite-signs-absolute", 1e-10, -1e-10, 1e-9, 1e-9, true),
        ("on-the-boundary", 10.0, 9.0, 0.1, 0.0, true),
        ("swapped-boundary", 9.0, 10.0, 0.1, 0.0, true),
        ("past-the-boundary", 10.0, 8.875, 0.1, 0.0, false),
        ("negative-values", -1.0, -1.0000000001, 1e-9, 0.0, true),
    ];
    for (name, a, b, rel_tol, abs_tol, want) in cases {
        assert_eq!(is_close(a, b, rel_tol, abs_tol), want, "{name}");
        assert_eq!(is_close(b, a, rel_tol, abs_tol), want, "{name} swapped");
    }
}

#[test]
fn non_finite() {
    assert!(!is_close(f64::NAN, f64::NAN, 1e-9, 0.0));
    assert!(is_close(f64::INFINITY, f64::INFINITY, 1e-9, 0.0));
    assert!(!is_close(f64::INFINITY, f64::NEG_INFINITY, 1e-9, 0.0));
    assert!(!is_close(f64::INFINITY, 1e308, 1e-9, 0.0));
}

#[test]
fn epsilon() {
    assert_eq!(f64::from_bits(1.0_f64.to_bits() + 1) - 1.0, f64::EPSILON);
}
is_close.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compare-floating-point-numbers/.

# is_close A B REL_TOL ABS_TOL
# Prints true if A and B are close, and false otherwise:
# |A - B| <= max(REL_TOL * max(|A|, |B|), ABS_TOL).
# Bash arithmetic has integers only, so the function gives the numbers to
# awk, which computes with floats.
is_close() {
  awk -v a="$1" -v b="$2" -v rel="$3" -v abst="$4" 'BEGIN {
    a += 0; b += 0; rel += 0; abst += 0
    if (a == b) { print "true"; exit }
    d = a - b; if (d < 0) d = -d
    m = (a < 0 ? -a : a); n = (b < 0 ? -b : b); if (n > m) m = n
    tol = rel * m; if (abst > tol) tol = abst
    print (d <= tol ? "true" : "false")
  }'
}
test_is_close.bats 30 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compare-floating-point-numbers/.

setup() {
  source "$BATS_TEST_DIRNAME/is_close.sh"
}

check() { # check WANT A B REL_TOL ABS_TOL; checks A, B and B, A
  local want=$1 got swapped
  got=$(is_close "$2" "$3" "$4" "$5")
  swapped=$(is_close "$3" "$2" "$4" "$5")
  [ "$got" = "$want" ] && [ "$swapped" = "$want" ] ||
    { printf 'got: %s %s\nwant: %s\n' "$got" "$swapped" "$want"; return 1; }
}

@test "equal" { check true 1.5 1.5 1e-9 0; }
@test "sum-of-tenths" { check true 0.30000000000000004 0.3 1e-9 0; }
@test "different" { check false 1.0 1.1 1e-9 0; }
@test "large-values" { check true 10000000000.0 10000000001.0 1e-9 0; }
@test "zero-and-zero" { check true 0.0 0.0 0 0; }
@test "one-ulp-apart" { check false 1.0 1.0000000000000002 0 0; }
@test "near-zero-relative" { check false 1e-12 0.0 1e-9 0; }
@test "near-zero-absolute" { check true 1e-12 0.0 1e-9 1e-9; }
@test "opposite-signs" { check false 1e-10 -1e-10 1e-9 0; }
@test "opposite-signs-absolute" { check true 1e-10 -1e-10 1e-9 1e-9; }
@test "on-the-boundary" { check true 10.0 9.0 0.1 0; }
@test "swapped-boundary" { check true 9.0 10.0 0.1 0; }
@test "past-the-boundary" { check false 10.0 8.875 0.1 0; }
@test "negative-values" { check true -1.0 -1.0000000001 1e-9 0; }

References

  1. Floating-Point Arithmetic, Issues and Limitations, Python 3 tutorial, the introduction
  2. math, Mathematical functions, Python 3 documentation, math.isclose, math.nextafter, math.ulp
  3. PEP 485, A Function for testing approximate equality, Handling of non-finite numbers; Behavior near zero; Symmetry
  4. Number.EPSILON, MDN Web Docs, the introduction
  5. Math, Java SE 27 API, ulp(double), nextUp(double)
  6. Numeric limits, C reference, cppreference.com, Limits of floating-point types
  7. nextafter, nexttoward, C reference, cppreference.com, the description
  8. Double.Epsilon Field, .NET API reference, Microsoft Learn, the definition; Remarks
  9. math, Go standard library, func Float64bits, func Nextafter
  10. f64, Rust standard library, EPSILON, to_bits
  11. Bash Reference Manual, version 5.3, 6.5 Shell Arithmetic
  12. awk, The Open Group Base Specifications Issue 8, Expressions in awk
  13. NaN, MDN Web Docs, Description

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source