Skip to content
Related Articles

Related Articles

math.Hypot Function in Golang With Examples
  • Last Updated : 01 Apr, 2020

Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You can find the hypotenuse, i.e., Sqrt(a*a + b*b) with the help of Hypot() function provided by the math package. So, you need to add a math package in your program with the help of the import keyword to access the Hypot() function.

Syntax:

func Hypot(a, b float64) float64
  • If you pass +Inf or -Inf in this function like Hypot(+Inf, b) or Hypot(-Inf, b), then this function will return +Inf.
  • If you pass +Inf or -Inf in this function like Hypot(a, +Inf) or Hypot(a, -Inf), then this function will return -Inf.
  • If you pass NaN in this function like Hypot(NaN, b) or Hypot(a, NaN), then this function will return NaN.

Example 1:




// Golang program to illustrate hypot() function
  
package main
  
import (
    "fmt"
    "math"
)
  
// Main function
func main() {
  
    // Finding hypotenuse
    // Using Hypot() function
    res_1 := math.Hypot(3, 4)
    res_2 := math.Hypot(-2, 6)
    res_3 := math.Hypot(4, math.Inf(1))
    res_4 := math.Hypot(math.NaN(), 5)
  
    // Displaying the result
    fmt.Printf("Result 1: %.1f", res_1)
    fmt.Printf("\nResult 2: %.1f", res_2)
    fmt.Printf("\nResult 3: %.1f", res_3)
    fmt.Printf("\nResult 4: %.1f", res_4)
  
}

Output:

Result 1: 5.0
Result 2: 6.3
Result 3: +Inf
Result 4: NaN

Example 2:




// Golang program to illustrate hypot() function
  
package main
  
import (
    "fmt"
    "math"
)
  
// Main function
func main() {
  
    // Finding hypotenuse
    // Using Hypot() function
    nvalue_1 := math.Hypot(3, 4)
    nvalue_2 := math.Hypot(-2, 6)
    res := nvalue_1 + nvalue_2
    fmt.Printf("%.5f + %.5f = %.5f",
            nvalue_1, nvalue_2, res)
  
}

Output:

5.00000 + 6.32456 = 11.32456

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :