Performing Math in Go is like many other programing languages in many ways.
Of course, the standard mathematical symbols apply:
| Operator | Description |
|---|---|
| + | Addition |
| – | Subtraction |
| * | Multiplication |
| / | Quotient |
| % | Remainder |
| & | Bitwise AND |
| | | Bitwise OR |
| ^ | Bitwise XOR |
| &^ | Bit clear (AND NOT) |
| << | Left shift |
| >> | Right shift (logical) |
The Math Package
There is also a math package you can import into your project. This is going to allow you access to both math functions and constants such as pi, e (the natural number), and others.
import (
"fmt"
"math"
)
In addition to the constants, there is a large number of mathematical functions in Go’s math package, with a brief description of each:
| Function | Description |
|---|---|
Abs(x) | Returns the absolute value of x. |
Acos(x) | Returns the arccosine, in radians, of x. |
Asin(x) | Returns the arcsine, in radians, of x. |
Atan(x) | Returns the arctangent, in radians, of x. |
Atan2(y, x) | Returns the arctangent of y/x, using the signs of the two values to determine the quadrant. |
Ceil(x) | Returns the smallest integer value greater than or equal to x. |
Cos(x) | Returns the cosine of x, where x is in radians. |
Exp(x) | Returns the base-e exponential of x, e**x. |
Floor(x) | Returns the largest integer value less than or equal to x. |
Hypot(x, y) | Returns sqrt(x² + y²), the Euclidean distance to (x, y). |
Log(x) | Returns the natural logarithm of x. |
Log10(x) | Returns the base-10 logarithm of x. |
Max(x, y) | Returns the larger of x or y. |
Min(x, y) | Returns the smaller of x or y. |
Pow(x, y) | Returns x raised to the power y. |
Round(x) | Rounds x to the nearest integer. |
Sin(x) | Returns the sine of x, where x is in radians. |
Sqrt(x) | Returns the square root of x. |
Tan(x) | Returns the tangent of x, where x is in radians. |
Trunc(x) | Returns the integer part of x, truncating any fractional component. |
Note that these are not all the math functions.
To use these, we’re going to put math. in front of the function names.
func main() {
result := math.Pow(3,5) // 3 * 3 * 3 * 3 * 3
fmt.Printf("%.1f", result) // print and format the value of the result
}
Notice that with our geometry functions (sine, cosine, tangent) those values are in radians, not degrees – just like in C/C++. In fact, several of the math functions are very similar to the one’s in C/C++, which means learning one, makes it easier to learn another.
Math in Go was originally found on Access 2 Learn