Math. Languages often have built-in math methods. With Go we import the math module. This provides commonly-used methods like Abs and Pow.
Math methods here operate on the float64 numeric type. So we cannot use an int directly with them—we must cast it first. This requires some extra complexity.
Math.Abs. Let us begin with Abs. We import the math module in the import-statement at the top. Next we introduce the "negative" integer.
Then We convert the "negative" number to a float64 and pass that to the math.Abs method. This returns a positive number.
package main
import (
"fmt""math"
)
func main() {
negative := -10
fmt.Println(negative)
// Use math.Abs to convert to a positive number.// ... We first convert to a float64.
result := math.Abs(float64(negative))
fmt.Println(result)
}-10
10
Pow, compute exponents. Pow raises one number to another. Here we compute the cube of 2, which is 8. We can also square numbers (with a second argument of 2) or use higher powers.
package main
import (
"fmt""math"
)
func main() {
// This can handle ints.
result := math.Pow(2, 3)
fmt.Println(result)
}8
Max, Min. The math.Max and math.Min methods both receive two float64 values. Max returns the higher of the two. Min returns the lower.
Note If both values are equal, the result is that value. A separate comparison must determine this case.
package main
import (
"fmt""math"
)
func main() {
small := float64(3)
large := float64(40)
// Get the larger of the two numbers.
max := math.Max(small, large)
fmt.Println(max)
// Get the smaller value.
min := math.Min(small, large)
fmt.Println(min)
}40
3
Floor. The floor is beneath us. With math.Floor, a number with a fractional part is always reduced so the fractional part does not exist. Both negative and positive numbers are reduced.
Signbit. This math method returns a bool. If the number is negative (has a sign bit) then Signbit returns true. For positive numbers, it returns false.
Fibonacci. In the Fibonacci sequence, each number is equal to the preceding two numbers. This sequence occurs often in the natural world. It has many uses.
Summary. Many math methods are available in the math package. We can implement math methods directly, with imperative statements. But this often leads to unneeded complexity.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 15, 2025 (edit link).