Skip to main content
Published on

Math Functions in Go

Share:

Introduction

Every modern programming language provides tools for mathematical operations, and Go is no exception. In this article, we will explore Go's math library in depth, focusing on the available functions and their practical applications.

The math Library

Go's math library is one of the most comprehensive in terms of mathematical functions.

import "math"

Basic Operations and Rounding Functions

In addition to fundamental operations, Go provides functions for handling rounding and absolute values:

value := -3.7
fmt.Println(math.Abs(value))    // 3.7
fmt.Println(math.Ceil(value))   // -3
fmt.Println(math.Floor(value))  // -4

Advanced Trigonometry

We not only have access to basic trigonometric functions, but also to their hyperbolic variants:

angle := math.Pi / 6  // 30 degrees
fmt.Println(math.Sin(angle))       // 0.5
fmt.Println(math.Cosh(angle))      // 1.140...

Power and Logarithm Functions

These functions are essential for advanced calculations:

base, exponent := 3.0, 2.0
fmt.Println(math.Pow(base, exponent))  // 9

In addition to natural logarithms, we can also compute logarithms in other bases:

value := 100.0
fmt.Println(math.Log10(value))  // 2

Special Functions

Go also incorporates functions for more specialized tasks, such as obtaining the minimum and maximum value between two numbers:

x, y := 3.2, 4.8
fmt.Println(math.Min(x, y))  // 3.2
fmt.Println(math.Max(x, y))  // 4.8

Using Mathematical Constants

Go predefines several useful mathematical constants, such as Pi and E:

fmt.Println(math.Pi)  // 3.141592653589793

Conclusion

Go's math library is vast and allows programmers to perform a variety of mathematical operations with ease and precision. We hope that, with this guide, you have a clearer understanding of its capabilities and can implement them effectively in your projects.

Happy coding!