Open In App

math.Hypot Function in Golang With Examples

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

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

Article Tags :