Go math.Hypot
math.Hypot returns the Euclidean length of two float64 components while avoiding unnecessary overflow and underflow.
A simple example
math.Hypot
- Start with Legs 3 and 4
- Do this Combine perpendicular lengths
- Result 5
package main
import "fmt"
import "math"
func main() {
fmt.Println(math.Hypot(3.0, 4.0))
}
5
Syntax
math.Hypot(x, y)
Run this example in Go
Save the program as main.go. Use Go 1.21 or later.
go run main.go
Measure diagonal travel without squaring distances
A map records two perpendicular components of a journey. Compute the straight-line distance using a method that can also handle component sizes for which intermediate squaring would lose range.
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Hypot(-3, 4))
fmt.Println(!math.IsInf(math.Hypot(1e200, 1e200), 0))
}
5 true
Changing the sign of one component leaves the distance unchanged. Using Hypot also preserves the finite result when the inputs are too large to square directly.
Go documentation for math.Hypot
Estimate a direct walk across campus
A student crosses a courtyard instead of following two perpendicular paths around it. Calculate the direct walking distance from the horizontal and vertical distances shown on the campus map.
package main
import (
"fmt"
"math"
)
func main() {
east := 6.0
north := 8.0
fmt.Printf("%.3f\n", math.Hypot(east, north))
}
10.000
Six blocks east and eight north form perpendicular sides. Their direct diagonal measures ten blocks.
Measure an exhibit’s diagonal cable route
An exhibition plan shows a socket 5 m east and 12 m north of a screen. A drafter marks the straight-line separation on the plan.
The perpendicular offsets form the legs of a right triangle.