The math Package in Golang

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.

Regular math functions

The most common math functions are as follows. Most of the functions work with float64 type here. We need to import the package at first.

import "math"

The math package contains many common functions that otherwise if implemented by the user may prove to be inefficient.

1. The Abs function

The Abs function produces the absolute value of a float64 number.

fmt.Println(math.Abs(-12.3))  // 12.3

2. The trigonometric functions

The trigonometric functions are sin, cos, tan, their inverse and hyperbolic functions.

fmt.Println(math.Sin(43))     // -0.8317747426285983
fmt.Println(math.Cos(57))     // 0.8998668269691938

3. The log function

The log function computes the logarithm of the float64 number provided.

fmt.Println(math.Log(89))     // 4.48863636973214

The Log10 does a base 10 logarithm on the input.

fmt.Println(math.Log10(90))   // 1.9542425094393248

4. The mod function

The mod function returns the remainder after division in float64.

fmt.Println(math.Mod(14, 5))  // 4

5. The ceiling and floor of a floating-point number

The ceil and floor compute the ceiling and the floor of a float64 number respectively. The ceiling and floor both are integers. Here is an example.

fmt.Println(math.Ceil(12.5))  // 13
fmt.Println(math.Floor(23.7)) // 23

6. Min and Max functions

The min and max functions compute the minimum and maximum of the two float64 provided.

fmt.Println(math.Min(23, 45)) // 23
fmt.Println(math.Max(23, 45)) // 45

7. The Pow function

The pow function computes power. The first argument is the base and the second is the exponent. It has multiple special cases.

fmt.Println(math.Pow(2, 16))   // 65536

8. The isNan() function

The isNan function checks whether the input is not a number.

fmt.Println(math.IsNaN(35))   // false

Important sub-packages

The math package contains important sub-packages such as the rand package which contains methods to generate random numbers. To generate cryptographically secure random numbers crypto/rand is recommended.

The big package implements arbitrary large integer handling. The bits package handles the bit manipulation segment.

To work with complex numbers the cmplx package is to be used.