The math Package
Square Roots and Powers
math.Sqrt computes a square root, and math.Pow raises a base to an exponent -- both operate on and return float64, so integer inputs need explicit conversion.
Example: Square Roots and Powers
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Sqrt(16))
fmt.Println(math.Pow(2, 10))
}
Login to try C/C++/Java/PHP code in the editor
Absolute Value and Comparisons
math.Abs returns a value's non-negative magnitude, while math.Max and math.Min return the larger or smaller of exactly two float64 arguments.
Example: Absolute Value and Comparisons
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Abs(-7.5))
fmt.Println(math.Max(3.2, 8.1))
fmt.Println(math.Min(3.2, 8.1))
}
Login to try C/C++/Java/PHP code in the editor
Rounding Numbers
math.Round rounds to the nearest whole number, math.Floor always rounds down, and math.Ceil always rounds up -- each returning a float64 representing that whole number.
Example: Rounding Numbers
package main
import (
"fmt"
"math"
)
func main() {
n := 4.6
fmt.Println(math.Round(n))
fmt.Println(math.Floor(n))
fmt.Println(math.Ceil(n))
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting math functions work on float64, requiring explicit conversion when starting with an int.
- Assuming math.Max/Min work on slices directly -- they only compare two float64 values at a time.
- Not checking for math.IsNaN or math.IsInf when a computation (like dividing by zero as a float) could produce a non-numeric result.
- The math package works with float64 values, so ints must be explicitly converted first.
- math.Sqrt, math.Pow, and math.Abs handle common numeric operations.
- math.Max and math.Min compare exactly two float64 values at a time.
- math.Round, Floor, and Ceil control how a float is rounded to a whole number.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: