Library contents

Go math.Hypot

math.Hypot returns the Euclidean length of two float64 components while avoiding unnecessary overflow and underflow.

A simple example

math.Hypot

  1. Start with Legs 3 and 4
  2. Do this Combine perpendicular lengths
  3. Result 5
The squared lengths sum to 25. Its square root is 5.
main.go
package main

import "fmt"
import "math"

func main() {
    fmt.Println(math.Hypot(3.0, 4.0))
}
Output
5

Syntax

Go 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.

First output line5
main.go
package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Println(math.Hypot(-3, 4))
	fmt.Println(!math.IsInf(math.Hypot(1e200, 1e200), 0))
}
Output
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

Advertisements

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.

From the programeast := 6.0
Result10.000
main.go
package main

import (
    "fmt"
    "math"
)

func main() {
    east := 6.0
    north := 8.0

    fmt.Printf("%.3f\n", math.Hypot(east, north))
}
Output
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.

GivenEast 5 m · north 12 m
Worked result13 m

The perpendicular offsets form the legs of a right triangle.