math.Nextafter Adjacent Floats

Walk the representable float grid with math.Nextafter — one step toward a target from below or above — to test rounding and spacing behavior.

GoData Integrity

Code

gosnippet
30 lines
package main

import (
	"fmt"
	"math"
)

func main() {
	x := 1.5

	// Nextafter(x, y):从 x 向 y 方向走一个可表示的浮点步长
	up := math.Nextafter(x, 2)
	down := math.Nextafter(x, 1)
	fmt.Println("next up:", up, "next down:", down)

	// 相邻可表示数之间没有第三个浮点数
	fmt.Println("nextafter(up, x) == x:", math.Nextafter(up, x) == x)

	// y == x 时原地返回;已到目标方向尽头则返回该端点
	fmt.Println("same target:", math.Nextafter(2.5, 2.5) == 2.5)
	fmt.Println("max float next:", math.Nextafter(math.MaxFloat64, math.Inf(1)))
	fmt.Println("zero next up:", math.Nextafter(0, 1))

	// 浮点比较容差:两数之间隔多少个可表示步
	steps := 0
	for v := x; v < up; v = math.Nextafter(v, up) {
		steps++
	}
	fmt.Println("steps from 1.5 to its neighbor:", steps)
}

Walking the float grid

The snippet is organized around the function main.

The loop for v := x; v < up; v = math.Nextafter(v, up) is the only repeated construct.

Watch out for

  • Zero packages pulled in — the runtime ships every API this code touches.

Putting it to use

Entry signature: func main()

The file’s steps show up in the output as next up:, nextafter(up, x) == x:, same target:.

Step arithmetic worth reading

down := math.Nextafter(x, 1)

Interactive Tools for This Topic

FAQ

What does math.Nextafter Adjacent Floats print when run?
No setup needed: run the file and look for labeled lines like `next up:`, `nextafter(up, x) == x:`, `same target:` in the output.