Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
184: Common math Package Functions
The math package in Go is one of those toolkits you'll use constantly, but it can be a bit finicky if you aren't paying attention to types. It doesn't try to be "smart" by guessing what you want; it expects everything to be a float64. If you give it an integer, the compiler will yell at you immediately.
To show you how this works in a real scenario, let's build a small utility to calculate the materials needed for a circular garden bed. We need to figure out the area for soil and the circumference for the edging border.
Setting up the Garden Geometry
First, I'll start by defining the radius of our garden. I'll use math.Pi for precision and math.Pow to handle the squaring of the radius. While r * r is technically faster, I prefer math.Pow when I'm dealing with formulas because it makes the code look more like the actual math I'm translating from a blueprint.
package main
import (
"fmt"
"math"
)
func main() {
radius := 4.5
area := math.Pi * math.Pow(radius, 2)
fmt.Printf("Garden area: %.2f square feet\n", area)
}
Hitting the float64 Wall
Now, let's say we want to add a "buffer zone" around the garden. I'll introduce an integer variable for the buffer width. Here is where I usually make my first mistake when I'm rushing: trying to mix types in a math function.
bufferWidth := 2 // integer
// I'll try to calculate the total radius including the buffer
totalRadius := radius + bufferWidth
// Then I'll try to find the square root of the total area for some reason
rootArea := math.Sqrt(totalRadius)
Wait—if I had defined radius as an int and bufferWidth as an int, and then tried to pass them into math.Sqrt, the code wouldn't even compile. Go is strict. You can't pass an int into math.Sqrt or math.Pow. I have to explicitly cast my variables to float64. It feels verbose, but it prevents those silent precision errors that haunt C++ developers.
// Correcting the approach:
totalRadius := radius + float64(bufferWidth)
rootArea := math.Sqrt(totalRadius)
fmt.Printf("Root area: %.2f\n", rootArea)
Rounding for the Hardware Store
In the real world, hardware stores don't sell 12.56 feet of edging; they sell it by the foot. This is where math.Ceil, math.Floor, and math.Round come into play. Since we can't have a gap in our garden border, we must always round up, regardless of the decimal.
If I used math.Round, 12.4 would become 12.0, and I'd be short on materials. I need math.Ceil (short for ceiling).
circumference := 2 * math.Pi * totalRadius
fmt.Printf("Exact circumference: %.2f\n", circumference)
// We need to buy whole feet of edging
materialNeeded := math.Ceil(circumference)
fmt.Printf("Purchase %.0f feet of edging\n", materialNeeded)
Comparing Garden Sizes
Finally, let's say we have two different garden designs and we want to know which one is larger. Instead of writing an if/else block, I can use math.Max. It's cleaner and more idiomatic when you just need the top value of two floats.
designA := 63.62
designB := 81.05
largest := math.Max(designA, designB)
fmt.Printf("The largest garden design is %.2f sq ft\n", largest)
Just remember: the math package is your friend, but it is a float64-only club. Cast your integers early, and use Ceil when you're buying materials so you don't have to drive back to the store.
📋 Practical Task
Build a Right-Triangle Hypotenuse Calculator
Create a program that calculates the hypotenuse of a right-angled triangle given two sides (a and b). Your program must:
- Define two variables for the sides as integers.
- Use
math.Powto square the sides andmath.Sqrtto find the square root of their sum (the Pythagorean theorem: $c = \sqrt{a^2 + b^2}$). - Handle the necessary type conversions from
inttofloat64to satisfy themathpackage. - Use
math.Roundto print the final hypotenuse length rounded to the nearest whole number.
There are no comments for now.