Square Root of a Number

To find square root of a number in Go language, use Sqrt() function of math package. Sqrt(x) returns the square root value of x.

In this tutorial, we will learn the syntax of Sqrt() function, and how to use this function to find the square root of a given number.

Syntax

The syntax of Sqrt() function is

math.Sqrt(x)

where x is a floating point value of type float64.

Please note that we have to import “math” package to use Sqrt() function.

Return Value

The function returns a floating point value of type float64.

ADVERTISEMENT

Examples

Square Root of Positive Number

In the following program, we take a positive value in x, and find its square root.

example.go

package main

import (
	"fmt"
	"math"
)

func main() {
	var x float64 = 9
	result := math.Sqrt(x)
	fmt.Println("Square root of 9 is :", result)
}

Output

Square root of 9 is : 3

Square Root of Negative Number

If a negative number is passed to Sqrt() function, then it returns NaN.

In the following program, we take a negative value in x, and find its square root.

example.go

package main

import (
	"fmt"
	"math"
)

func main() {
	var x float64 = -9
	result := math.Sqrt(x)
	fmt.Println("Square root of -9 is :", result)
}

Output

Square root of -9 is : NaN

Conclusion

In this Golang Tutorial, we learned how to find square root of a given number in Go language, with example programs.