Float Nearly Equal Epsilon Compare

Compare floats through a small epsilon instead of ==, since 0.1+0.2 != 0.3 while positive infinity still equals itself.

GoData Integrity

Code

gosnippet
25 lines
package main

import (
	"fmt"
	"math"
)

const epsilon = 1e-9

func nearlyEqual(a, b float64) bool {
	if a == b {
		return true // exact match, and +Inf/-Inf equal themselves
	}
	return math.Abs(a-b) < epsilon
}

func main() {
	sum := 0.1 + 0.2
	fmt.Println("0.1 + 0.2 ==", sum)
	fmt.Println("direct 0.3 compare:", sum == 0.3) // false on IEEE-754
	fmt.Println("epsilon compare:  ", nearlyEqual(sum, 0.3))

	fmt.Println("inf equals inf:", nearlyEqual(math.Inf(1), math.Inf(1)))
	fmt.Println("far apart:      ", nearlyEqual(1.0, 1.1))
}

How this file behaves — Float Nearly Equal Epsilon Compare

Everything happens inside the functions nearlyEqual and main.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

Signature worth noting: func nearlyEqual(a, b float64) bool

The run prints these labels: 0.1 + 0.2 ==, direct 0.3 compare:, epsilon compare: — when the file runs.

The demo flow inside main is nearlyEqual — run the file to see it end to end.

Key statements

func nearlyEqual(a, b float64) bool {
	if a == b {
		return true // exact match, and +Inf/-Inf equal themselves
	}
	return math.Abs(a-b) < epsilon
}

Interactive Tools for This Topic

FAQ

What does Float Nearly Equal Epsilon Compare print when run?
Running the file directly is enough — expect labeled output lines such as `0.1 + 0.2 ==`, `direct 0.3 compare:`, `epsilon compare:`.