Math functions in Golang





Hey guys in this post, we will discuss some of the math functions that Golang provided out of the box.

The math package in Go contains entirely of many math functions that can be used to do different things. Here are the main math functions that are used frequently.

package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Println(math.Max(9, 5))
	fmt.Println(math.Min(5, 9))
	fmt.Println(math.Abs(-10))
	fmt.Println((math.Remainder(5, 4)))
	fmt.Println(math.Sqrt(10))
	fmt.Println(math.Round(10.4))
	fmt.Println(math.IsNaN(34))
}

Output:

PS C:\workspace\go lang workspace> go run .\MathFunctions.go
9
5
10
1
3.1622776601683795
10
false

At the top, first we need to import the math package using import keyword

import (
	"fmt"
	"math"
)
  • math.Max(): Max returns the largest number between the two numbers x and y.
  • math.Min(): Min returns the smallest number between the two numbers x and y.
  • math.Abs(): Abs returns the absolute value of the specified number.
  • math.Remainder(): Remainder returns the remainder of the specified numbers x/y.
  • math.Sqrt(): Sqrt returns the square root of given number.
  • math.Round(): Round returns the nearest integer, rounding half away from zero.
  • math.IsNaN(): IsNaN tells whether given values is not-a-number. It returns boolean.

These are some of the most commonly used math functions.

Read more about math functions: https://pkg.go.dev/math

That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.



About the author

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *