The math Package
math.Sqrt(x)
math.Pow(x, y)
math.Max(a, b)
math.Floor(x)
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
// Every Go file belongs to a package; main builds an executable
package main
// Import the packages this program uses
import (
"fmt"
"math"
)
// main is where the program starts running
func main() {
// Print the values followed by a newline
fmt.Println(math.Sqrt(16))
// Print the values followed by a newline
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
// Every Go file belongs to a package; main builds an executable
package main
// Import the packages this program uses
import (
"fmt"
"math"
)
// main is where the program starts running
func main() {
// Print the values followed by a newline
fmt.Println(math.Abs(-7.5))
// Print the values followed by a newline
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
// Every Go file belongs to a package; main builds an executable
package main
// Import the packages this program uses
import (
"fmt"
"math"
)
// main is where the program starts running
func main() {
// Short declaration: create n and infer the type
n := 4.6
// Print the values followed by a newline
fmt.Println(math.Round(n))
// Print the values followed by a newline
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: