Golang math.Sqrt() Function with Examples

Golang | math.Sqrt() Function: Here, we are going to learn about the Sqrt() function of the math package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 03, 2021

math.Sqrt()

The Sqrt() function is an inbuilt function of the math package which is used to get the square root of the given value.

It accepts a parameter (x) and returns the square root of x.

Also read: Find the square root of complex numbers in Go.

Syntax:

func Sqrt(x float64) float64

Parameter(s):

  • x : The value whose square root is to be found.

Return Value:

The return type of Sqrt() function is a float64, it returns the square root of the given value (parameter).

Special cases:

  • Sqrt(+Inf) = +Inf
    If the parameter is +Inf, the function returns the same value (+Inf).
  • Sqrt(±0) = ±0
    If the parameter is ±0, the function returns the same value (±0).
  • Sqrt(x < 0) = NaN
    If the parameter is less than 0, the function returns NaN.
  • Sqrt(NaN) = NaN
    If the parameter is NaN, the function returns the same value (NaN).

Example 1:

// Golang program to demonstrate the
// example of math.Sqrt() Function

package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Println(math.Sqrt(25))
	fmt.Println(math.Sqrt(225))
	fmt.Println(math.Sqrt(64.25))
	fmt.Println(math.Sqrt(123.45))

	fmt.Println(math.Sqrt(1))
	fmt.Println(math.Sqrt(0))

	fmt.Println(math.Sqrt(-1))
	fmt.Println(math.Sqrt(math.Inf(-1)))
	fmt.Println(math.Sqrt(math.Inf(1)))
	fmt.Println(math.Sqrt(math.NaN()))
}

Output:

5
15
8.0156097709407
11.110805551354051
1
0
NaN
NaN
+Inf
NaN

Example 2:

// Golang program to demonstrate the
// example of math.Sqrt() Function

package main

import (
	"fmt"
	"math"
)

func main() {
	var x float64
	var SqrtX float64

	x = 225
	SqrtX = math.Sqrt(x)
	fmt.Println("Square root of", x, "is", SqrtX)

	x = 64
	SqrtX = math.Sqrt(x)
	fmt.Println("Square root of", x, "is", SqrtX)

	x = 1.5
	SqrtX = math.Sqrt(x)
	fmt.Println("Square root of", x, "is", SqrtX)

	x = 1
	SqrtX = math.Sqrt(x)
	fmt.Println("Square root of", x, "is", SqrtX)

	x = 0
	SqrtX = math.Sqrt(x)
	fmt.Println("Square root of", x, "is", SqrtX)

	x = -25
	SqrtX = math.Sqrt(x)
	fmt.Println("Square root of", x, "is", SqrtX)

	x = math.Inf(-1)
	SqrtX = math.Sqrt(x)
	fmt.Println("Square root of", x, "is", SqrtX)

	x = math.Inf(1)
	SqrtX = math.Sqrt(x)
	fmt.Println("Square root of", x, "is", SqrtX)
}

Output:

Square root of 225 is 15
Square root of 64 is 8
Square root of 1.5 is 1.224744871391589
Square root of 1 is 1
Square root of 0 is 0
Square root of -25 is NaN
Square root of -Inf is NaN
Square root of +Inf is +Inf

Golang math Package Constants and Functions »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.