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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.IEEE 754 ConverterConvert decimal floats to and from IEEE 754 single- and double-precision bit patterns in hex and binary.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.