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.
Code
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
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.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.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.