Golang Math Package Examples [Tutorial]


GO

Author: Tuan Nguyen
Reviewer: Deepak Prasad

The built-in math package in Go is made up entirely of math functions and constants that can be used to perform various tasks. Most of the functions work with float64 type here. We need to import the package first.

import "math"

Package math provides basic constants and mathematical functions.

 

GO Math Constants

Math package provides some Mathematical constants:

const (
	E   = 2.71828182845904523536028747135266249775724709369995957496696763 // https://oeis.org/A001113
	Pi  = 3.14159265358979323846264338327950288419716939937510582097494459 // https://oeis.org/A000796
	Phi = 1.61803398874989484820458683436563811772030917980576286213544862 // https://oeis.org/A001622

	Sqrt2   = 1.41421356237309504880168872420969807856967187537694807317667974 // https://oeis.org/A002193
	SqrtE   = 1.64872127070012814684865078781416357165377610071014801157507931 // https://oeis.org/A019774
	SqrtPi  = 1.77245385090551602729816748334114518279754945612238712821380779 // https://oeis.org/A002161
	SqrtPhi = 1.27201964951406896425242246173749149171560804184009624861664038 // https://oeis.org/A139339

	Ln2    = 0.693147180559945309417232121458176568075500134360255254120680009 // https://oeis.org/A002162
	Log2E  = 1 / Ln2
	Ln10   = 2.30258509299404568401799145468436420760110148862877297603332790 // https://oeis.org/A002392
	Log10E = 1 / Ln10
)

It also defines integer limit values:

const (
	MaxInt    = 1<<(intSize-1) - 1
	MinInt    = -1 << (intSize - 1)
	MaxInt8   = 1<<7 - 1
	MinInt8   = -1 << 7
	MaxInt16  = 1<<15 - 1
	MinInt16  = -1 << 15
	MaxInt32  = 1<<31 - 1
	MinInt32  = -1 << 31
	MaxInt64  = 1<<63 - 1
	MinInt64  = -1 << 63
	MaxUint   = 1<<intSize - 1
	MaxUint8  = 1<<8 - 1
	MaxUint16 = 1<<16 - 1
	MaxUint32 = 1<<32 - 1
	MaxUint64 = 1<<64 - 1
)

 

Using math constants to calculate the area and circumference of a circle

Example of using constants in Go to read the radius input and calculate the area and circumference of a circle:

package main

import (
	"fmt"
	"math"
)

func main() {
	var rad float64
	var area float64
	var ci float64

	//user input the radius of the Cirle
	fmt.Print("Enter radius of Circle : ")
	fmt.Scanln(&rad)
	area = math.Pi * rad * rad

	fmt.Println("Area of Circle is : ", area)
	ci = 2 * math.Pi * rad
	fmt.Println("Circumference of Circle is : ", ci)
}

Output:

Enter radius of Circle : 1.2
Area of Circle is :  4.523893421169302
Circumference of Circle is :  7.5398223686155035

 

Math Functions

Syntax Definition Example
func Abs(x float64) float64 Abs returns the absolute value of x. fmt.Println(math.Abs(-2)) //2 fmt.Println(math.Abs(2))  //2
func Acos(x float64) float64, func Acosh(x float64) float64, func Asin(x float64) float64, func Asinh(x float64) float64, func Atan(x float64) float64, func Atan2(y, x float64) float64, func Atanh(x float64) float64, func Cos(x float64) float64, func Cosh(x float64) float64, func Sin(x float64) float64, func Sincos(x float64) (sin, cos float64)   Trigonometric functions fmt.Printf("%.2f", math.Atanh(0)) //0.00
func Cbrt(x float64) float64 Cbrt returns the cube root of x. fmt.Printf("%.2f\n", math.Cbrt(27)) //3
func Ceil(x float64) float64 Ceil returns the least integer value greater than or equal to x. c := math.Ceil(1.49) fmt.Printf("%.1f", c) //2.0
func Copysign(f, sign float64) float64 Copysign returns a value with the magnitude of f and the sign of sign. fmt.Printf("%.2f", math.Copysign(3.2, -1)) //-3.20
func Exp(x float64) float64, Exp returns e**x, the base-e exponential of x. fmt.Printf("%.2f\n", math.Exp(1)) //2.72 fmt.Printf("%.2f\n", math.Exp(2)) //7.39 fmt.Printf("%.2f\n", math.Exp(-1)) //0.37
func Exp2(x float64) float64, func Expm1(x float64) float64 base-e exponential functions
func Floor(x float64) float64 Floor returns the greatest integer value less than or equal to x. c := math.Floor(1.51) fmt.Printf("%.1f", c) //1.0
func IsNaN(f float64) (is bool) IsNaN reports whether f is an IEEE 754 “not-a-number” value.
func Log(x float64) float64 Log returns the natural logarithm of x. x := math.Log(1) fmt.Printf("%.1f\n", x) //0.0
y := math.Log(2.7183) fmt.Printf("%.1f\n", y) //1.0
func Log10(x float64) float64 Log10 returns the decimal logarithm of x. The special cases are the same as for Log. fmt.Printf("%.1f", math.Log10(100)) //2.0
func Max(x, y float64) float64, func Min(x, y float64) float64 Max returns the larger/smaller of x or y.
func Mod(x, y float64) float64 Mod returns the floating-point remainder of x/y. The magnitude of the result is less than y and its sign agrees with that of x. c := math.Mod(7, 4) fmt.Printf("%.1f", c) //3.0
func Pow(x, y float64) float64 Pow returns x**y, the base-x exponential of y. c := math.Pow(2, 3) fmt.Printf("%.1f", c) //8.0
func Remainder(x, y float64) float64 Remainder returns the IEEE 754 floating-point remainder of x/y. fmt.Printf("%.1f", math.Remainder(100, 30)) //10.0
func Round(x float64) float64 Round returns the nearest integer, rounding half away from zero. p := math.Round(10.5) fmt.Printf("%.1f\n", p) //11.0 n := math.Round(-10.5) fmt.Printf("%.1f\n", n)  //-11.0
func RoundToEven(x float64) float64 RoundToEven returns the nearest integer, rounding ties to even.
func Signbit(x float64) bool Signbit reports whether x is negative or negative zero.
func Sqrt(x float64) float64 Sqrt returns the square root of x. const (a = 3 b = 4) c:= math.Sqrt(a*a + b*b) fmt.Printf("%.1f", c) //5.0
func Trunc(x float64) float64 Trunc returns the integer value of x. fmt.Printf("%.2f\n", math.Trunc(math.Pi))  //3.00 fmt.Printf("%.2f\n", math.Trunc(-1.2345))  //-1.00

For special cases for each function, visit the Go Math package documentation.

 

Using math functions to solve quadratic problem

Here's a quick example on how to do quadratic calculations (ax2+bx+c) in Golang. This program accepts three floating point values from the stdin and uses the quadratic formula to calculate the roots.

package main

import (
	"fmt"
	"math"
)

func main() {

	var a, b, c, x1, x2, discriminant float64

	fmt.Print("Enter a, b, c = ")
	fmt.Scanln(&a, &b, &c)

	//use Pow function
	discriminant = math.Pow(b, 2) - (4 * a * c)

	if discriminant > 0 {
		// use Sqrt function
		x1 = (-b + math.Sqrt(discriminant)/(2*a))
		x2 = (-b - math.Sqrt(discriminant)/(2*a))
		fmt.Println("x1 = ", x1, " and x2 = ", x2)
	} else if discriminant == 0 {
		x1 = -b / (2 * a)
		x2 = -b / (2 * a)
		fmt.Println("x1 = ", x1, " and x2 = ", x2)
	} else if discriminant < 0 {
		fmt.Println("Can not solve the problem")
	}
}

Output:

Enter a, b, c = 1 2 1
x1 =  -1  and x2 =  -1

Enter a, b, c = 1 2 3
Can not solve the problem

 

Math sub-packages

The math package includes useful sub-packages such as the rand package, which includes methods for generating random numbers. Crypto/rand is recommended for generating cryptographically secure random numbers. The big package handles arbitrary large integers. The bit manipulation segment is handled by the bits package. The cmplx package should be used when working with complex numbers.

Package Content
big Package big implements arbitrary-precision arithmetic (big numbers).
bits Package bits implements bit counting and manipulation functions for the predeclared unsigned integer types.
cmplx Package cmplx provides basic constants and mathematical functions for complex numbers.
Rand Package rand implements pseudo-random number generators unsuitable for security-sensitive work.

 

Using cmplx package to work with complex number

Here is an example of using cmplx package to do some math operations such as Pow, Sqrt with complex number

package main

import (
	"fmt"
	"math/cmplx"
)

func main() {
	comp1 := complex(1, -2)        // constructor init
	comp2 := 2 + 3i                // complex initializer syntax a + ib
	comp3 := comp1 + comp2         // addition just like other variables
	compPow := cmplx.Pow(comp3, 2) // pow with complex number
	compSqrt := cmplx.Sqrt(comp3)  // square with complex number
	fmt.Println("Add: ", comp3)    
	re := real(comp3)              // get real part
	im := imag(comp3)              // get imaginary part
	fmt.Println(re, im)
	fmt.Println(compPow)
	fmt.Println(compSqrt)
}

Output:

Add:  (3+1i)
3 1
(8.000000000000002+6.000000000000001i)
(1.755317301824428+0.28484878459314106i)

You can refer to generate random string to know how to use math/rand to generate a random string.

 

Summary

This section provided a more in-depth introduction to the math package in Golang's standard library. We covered a few key functions and constants in the main math package, as well as a glimpse of other sub-packages such as rand, cmplx, and bits.

 

References

https://pkg.go.dev/math
https://pkg.go.dev/math/bits@go1.19.1
https://pkg.go.dev/math/big@go1.19.1
https://pkg.go.dev/math/cmplx@go1.19.1
https://pkg.go.dev/math/rand@go1.19.1

 

Tuan Nguyen

Tuan Nguyen

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment