Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Square Root of a number in Go (Golang)

Posted on March 26, 2023March 26, 2023 by admin

Table of Contents

  • Overview
  • Code:

Overview

math package of GO provides a Sqrt method that can be used to get the cube root of that number.

Below is the signature of the function. It takes input a float and also returns a float.

func Sqrt(x float64) float64

Some special cases of Sqrt function are

  • Sqrt(±0) = ±0
  • Sqrt(±Inf) = ±Inf
  • Sqrt(x < 0) = NaN
  • Sqrt(NaN) = NaN

Code:

package main
import (
"fmt"
"math"
)
func main() {
//Square root of a integer
res := math.Sqrt(4)
fmt.Println(res)
//Square root of a integer
res = math.Sqrt(9)
fmt.Println(res)
//Square Root of a float
res = math.Sqrt(30.33)
fmt.Println(res)
//Square Root of a negative number
res = math.Sqrt(-9)
fmt.Println(res)
}

Output:

2
3
5.5072679252057455
  • go
  • golang
  • math
  • square root
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP