Float NaN And Inf Guards

Sqrt of negatives yields NaN that fails every comparison, overflow yields Inf; IsNaN and IsInf guards keep NaN out of aggregated sums before it spreads.

GoData Integrity

Code

gosnippet
36 lines
package main

import (
	"fmt"
	"math"
)

func main() {
	// Sqrt 负数产生 NaN;浮点乘法溢出产生 ±Inf(须用变量触发,常量溢出会编译报错)
	nan := math.Sqrt(-1)
	limit := 1e308
	inf := limit * 10

	// NaN 与任何值比较都是 false,包括与自身相等:等值检查必须换成 IsNaN
	fmt.Println("nan == nan:", nan == nan)
	fmt.Println("IsNaN:", math.IsNaN(nan))

	// Inf 有符号:IsInf 第二个参数传 0 表示任一符号,Signbit 区分正负
	fmt.Println("IsInf:", math.IsInf(inf, 0), "signbit(-inf):", math.Signbit(-inf))

	// Inf 参与算术不再 panic,但 Inf-Inf 塌缩成 NaN
	fmt.Println("inf - inf is NaN:", math.IsNaN(inf-inf))

	// 聚合前过滤非法值:一个 NaN 就会把整列求和污染成 NaN
	samples := []float64{3.5, nan, 12.25, inf, -8}
	sum := 0.0
	count := 0
	for _, v := range samples {
		if math.IsNaN(v) || math.IsInf(v, 0) {
			continue
		}
		sum += v
		count++
	}
	fmt.Printf("valid %d sum %.2f\n", count, sum)
}

The internal choreography

Float NaN And Inf Guards reduces to the function main.

Repetition is confined to for _, v := range samples — the rest of the file is straight-line.

Using it

The run emits 5 labeled sections — nan == nan:, IsNaN:, IsInf:, inf - inf is NaN:, valid — one per step.

Key statements

for _, v := range samples {
	if math.IsNaN(v) || math.IsInf(v, 0) {
		continue
	}
	sum += v
	count++
}

Interactive Tools for This Topic

FAQ

What does Float NaN And Inf Guards print when run?
Execute the whole file; each printed line is prefixed with a label like `nan == nan:`, `IsNaN:`, `IsInf:`.