Go .Hypot()
The math.Hypot() function in Go calculates the Euclidean distance (hypotenuse) between two points in a coordinate system. It returns the square root of the sum of the squares of two given numbers, mathematically expressed as sqrt(x² + y²). This function is particularly useful in geometric calculations, distance measurements, and mathematical computations where precision and overflow handling are crucial.
It is commonly used in computer graphics, game development, physics simulations, navigation systems, and any application requiring distance calculations between two points. It provides a robust implementation that handles edge cases like infinite values and NaN (Not a Number) gracefully, making it reliable for production applications.
Syntax
math.Hypot(x, y)
Parameters:
x: The first floating-point number representing one side of the right triangley: The second floating-point number representing the other side of the right triangle
Return value:
The function returns a float64 value representing the hypotenuse of the right triangle formed by the two input parameters.
Special Cases:
Hypot(±Inf, y)returns+InfHypot(x, ±Inf)returns+InfHypot(NaN, y)returnsNaNHypot(x, NaN)returnsNaN
Example 1: Basic Hypotenuse Calculation
This example demonstrates the basic usage of math.Hypot() to calculate the hypotenuse of a right triangle:
package mainimport ("fmt""math")func main() {// Calculate hypotenuse for a right triangle with sides 3 and 4side1 := 3.0side2 := 4.0// Using math.Hypot() functionhypotenuse := math.Hypot(side1, side2)fmt.Printf("Side 1: %.1f\n", side1)fmt.Printf("Side 2: %.1f\n", side2)fmt.Printf("Hypotenuse: %.1f\n", hypotenuse)// Verify with manual calculationmanual := math.Sqrt(side1*side1 + side2*side2)fmt.Printf("Manual calculation: %.1f\n", manual)}
The output of the above code is:
Side 1: 3.0Side 2: 4.0Hypotenuse: 5.0Manual calculation: 5.0
This example shows how math.Hypot(3, 4) correctly returns 5.0, which is the hypotenuse of a classic 3-4-5 right triangle.
Example 2: Distance Between Two Points
This example demonstrates using math.Hypot() to calculate the distance between two points in a 2D coordinate system:
package mainimport ("fmt""math")func main() {// Define two points in 2D spacex1, y1 := 1.0, 2.0 // Point Ax2, y2 := 4.0, 6.0 // Point B// Calculate the differencesdeltaX := x2 - x1deltaY := y2 - y1// Calculate distance using math.Hypot()distance := math.Hypot(deltaX, deltaY)fmt.Printf("Point A: (%.1f, %.1f)\n", x1, y1)fmt.Printf("Point B: (%.1f, %.1f)\n", x2, y2)fmt.Printf("Delta X: %.1f\n", deltaX)fmt.Printf("Delta Y: %.1f\n", deltaY)fmt.Printf("Distance between points: %.2f\n", distance)// Alternative calculation for comparisonalternative := math.Sqrt(deltaX*deltaX + deltaY*deltaY)fmt.Printf("Alternative calculation: %.2f\n", alternative)}
The output of the above code is:
Point A: (1.0, 2.0)Point B: (4.0, 6.0)Delta X: 3.0Delta Y: 4.0Distance between points: 5.00Alternative calculation: 5.00
This example shows how to use math.Hypot() to calculate the Euclidean distance between two points in a coordinate system, which is essential for navigation and graphics applications.
Example 3: Handling Special Cases
This example demonstrates how math.Hypot() handles special cases, including infinite values and NaN:
package mainimport ("fmt""math")func main() {// Test with normal valuesfmt.Printf("Normal case - Hypot(3, 4): %.2f\n", math.Hypot(3, 4))// Test with positive infinityfmt.Printf("Positive infinity - Hypot(+Inf, 5): %.2f\n",math.Hypot(math.Inf(1), 5))// Test with negative infinityfmt.Printf("Negative infinity - Hypot(-Inf, 5): %.2f\n",math.Hypot(math.Inf(-1), 5))// Test with NaN (Not a Number)fmt.Printf("NaN case - Hypot(NaN, 5): %.2f\n",math.Hypot(math.NaN(), 5))// Test with zero valuesfmt.Printf("Zero case - Hypot(0, 0): %.2f\n", math.Hypot(0, 0))// Test with large numbers (overflow protection)largeNum := 1e200fmt.Printf("Large numbers - Hypot(%.0e, %.0e): %.2e\n",largeNum, largeNum, math.Hypot(largeNum, largeNum))}
The output of this code is:
Normal case - Hypot(3, 4): 5.00Positive infinity - Hypot(+Inf, 5): +InfNegative infinity - Hypot(-Inf, 5): +InfNaN case - Hypot(NaN, 5): NaNZero case - Hypot(0, 0): 0.00Large numbers - Hypot(1e+200, 1e+200): 1.41e+200
This example illustrates how math.Hypot() gracefully handles edge cases, returning appropriate values for infinite inputs and NaN values while providing overflow protection for very large numbers.
Frequently Asked Questions
1. What’s the difference between using math.Hypot() and manually calculating math.Sqrt(x*x + y*y)?
math.Hypot() provides better precision and more robustly handles overflow/underflow cases. Manual calculation might result in overflow or loss of precision for very large or very small numbers, while math.Hypot() is specifically designed to avoid these issues.
2. Can I use math.Hypot() with integer values?
Yes, but math.Hypot() only accepts float64 values. While numeric literals like math.Hypot(3, 4) are automatically treated as float64, you’ll need to explicitly convert integer variables using float64() before passing them to the function.
3. Is math.Hypot() suitable for calculating distances in 3D space?
math.Hypot() only accepts two parameters, so it’s designed for 2D calculations. For 3D distance calculations, you would need to use math.Sqrt(x*x + y*y + z*z) or combine multiple calls to math.Hypot().
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Go on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn how to use Go (Golang), an open-source programming language supported by Google!
- Beginner Friendly.6 hours