Henceforth, learning how to perform various mathematical operations as a programmer is very vital. No, I don’t mean you have to be a math whizz, though beneficial. This is because most programming languages provide you with tools and methods to carry out mathematical operations.

In this guide, we will explore the math package in the Go programming language.

## Golang Math Package

In Go, we get access to math functions by importing the math package. We can do this using the import clause as:

Once imported, you will get access to some of the most practical mathematical functions.

## Trig Functions

The Go math package provides us with trigonometric functions such as sin, tan, cos, their respective inverses, and hyperbolic.

An example of how to use these functions is as shown:

import (

"fmt"

"math"

)

func main() {

fmt.Printf("Sin: %.2f\n", math.Sin(66.32))

fmt.Printf("Tan: %.2f\n", math.Tan(43.01))

fmt.Printf("Cos: %.2f\n", math.Cos(34.23))

fmt.Printf("sin-1: %.2f\n", math.Asin(.913545))

fmt.Printf("tan-1: %.2f\n", math.Atan(.20791169))

fmt.Printf("cos-1: %.2f\n", math.Acos(.32704482))

fmt.Printf("sin-1(h): %.2f\n", math.Asinh(50.4))

fmt.Printf("tan-1(h): %.2f\n", math.Acos(.70))

fmt.Printf("cos-1(h): %.2f\n", math.Acos(.82))

}

The above example program uses math functions to calculate sin, tan, cos, their inverse and hyperbolic inverses.

The resulting values are as:

Sin: -0.34

sin-1: 1.15

tan-1: 0.20

cos-1: 1.24

sin-1(h): 4.61

tan-1(h): 0.80

cos-1(h): 0.61

## Absolute Function

The abs function from the math package allows to get the absolute number of the specified value. An example code is as shown:

## The Log Function

You can also determine the natural logarithm of a number using the log function. An example usage is as shown:

4.605170185988092

You can also use the log10 to return the log a number to base 10.

An example is as shown:

2

## Square Root

To determine the square root of a number, use the Sqrt() method. An example code is as shown:

The code above returns:

## Mod Value

You can determine the remainder of a division between two values using the mode method. An example:

fmt.Println(math.Mod(10, 5)) // remainder = 0

## Min & Max

If you have two values, you can determine their minimum and maximum value using the min() and max() methods respectively.

fmt.Println(math.Max(10, 3)) // return 10

## Power

To calculate the power of a value to a specified base value, we can use the pow() method. It takes the number and the base as the arguments.

## Not a Number

If you want to check if a provided value is or isn’t a number, you can use the isNaN() method. This method returns true if the value is not a number, a false if otherwise.

## Closing

This was a short guide introducing you to the math package. Using the methods in this package, you can perform a plethora of operations without building custom methods.

You can check the documentation: https://pkg.go.dev/math

Thanks for reading!