The math Package
Start with The math Package
The math package provides numeric functions and constants for floating-point calculations.
What you’ll learn
- Explain the main purpose of the math package.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
math.Sqrt computes a square root, math.Pow computes powers, and math.Abs obtains a floating-point magnitude. Functions such as Sqrt usually operate on float64, so integer variables may require explicit conversion.
Floating-point values are approximations; direct equality is often inappropriate for calculated results. The math package’s Pi constant can be used in geometric formulas.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"math"
)
func main() {
radius := 3.0
area := math.Pi * math.Pow(radius, 2)
fmt.Printf("Area: %.2f\n", area)
fmt.Println("Square root:", math.Sqrt(81))
}
Output
Area: 28.27
Square root: 9Trace what the program does
Pow computes radius squared and Pi multiplies it to form a circle’s area, displayed to two decimal places. Sqrt(81) evaluates to 9.
Avoid common mistakes
- math.Sqrt returns float64 rather than int.
- Do not use direct == for most approximate floating-point calculations.
Try it yourself
Compute the circumference of a radius-5 circle using math.Pi and print two decimals.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced The math Package in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.