Math and Random

Back

Loading concept...

🎲 Go’s Magic Toolbox: Math & Random Numbers

Imagine you have a magic calculator that can do any math you want, and a mystery box that gives you surprise numbers. That’s what Go’s math and math/rand packages are!


đź§® Meet Your Math Helper

Think of the math package like having a super-smart friend who knows all the math tricks. You just ask, and they give you the answer instantly!

Getting Started

import "math"

That’s it! Now you have superpowers! 🦸


âž• Basic Math Operations

Absolute Value - “How Far From Zero?”

Imagine you’re standing at your house (that’s zero). Whether you walk 5 steps forward (+5) or 5 steps backward (-5), you still walked 5 steps total.

distance1 := math.Abs(-7.5)  // 7.5
distance2 := math.Abs(7.5)   // 7.5

🎯 Real life: Calculating how far you traveled, no matter which direction!


Floor & Ceil - “Rounding to Whole Numbers”

Floor is like dropping a ball - it falls DOWN to the nearest whole number.

Ceil (ceiling) is like a balloon - it floats UP to the nearest whole number.

dropped := math.Floor(3.7)   // 3
floated := math.Ceil(3.2)    // 4

// Even with negatives!
math.Floor(-2.3)  // -3 (goes down)
math.Ceil(-2.3)   // -2 (goes up)
graph TD A["3.7"] --> B{Which way?} B -->|Floor ⬇️| C["3"] B -->|Ceil ⬆️| D["4"]

Round - “The Fairest Choice”

Round looks at the decimal. If it’s 0.5 or more, go up. Otherwise, go down.

math.Round(2.4)   // 2
math.Round(2.5)   // 3
math.Round(2.6)   // 3

Min & Max - “Who’s the Winner?”

Like a race! Max finds the fastest, Min finds the slowest.

bigger := math.Max(10.5, 20.3)   // 20.3
smaller := math.Min(10.5, 20.3) // 10.5

Power - “Multiplying By Itself”

Pow is like asking: “What if I multiply this number by itself… many times?”

// 2 Ă— 2 Ă— 2 = 8
result := math.Pow(2, 3)  // 8

// 5 Ă— 5 = 25
square := math.Pow(5, 2)  // 25

Square Root - “The Reverse of Squaring”

If 5 × 5 = 25, then the square root of 25 is 5. It’s like asking: “What number, times itself, gives me this?”

math.Sqrt(25)   // 5
math.Sqrt(100)  // 10
math.Sqrt(2)    // 1.414...

Special Math Constants

Go gives you some magic numbers that mathematicians love:

math.Pi      // 3.14159... (circles!)
math.E       // 2.71828... (growth!)
math.Phi     // 1.61803... (golden ratio!)

🎲 The Mystery Box: Random Numbers

Now for the fun part! The math/rand package is like having a mystery box that gives you surprise numbers.

Getting Started with Random

import (
    "math/rand"
    "time"
)

🌱 The Seed: Where Random Begins

Here’s a secret: computers can’t really be “random.” They follow patterns. The seed is the starting point of that pattern.

Same seed = Same “random” numbers every time!

// Old way (before Go 1.20)
rand.Seed(time.Now().UnixNano())

// New way (Go 1.20+) - automatic!
// Just use rand functions directly

Think of it like a music playlist on “shuffle.” If you start at the same point, you get the same order!


🎯 Getting Random Numbers

Random Integer (0 to n-1)

// Random number from 0 to 99
num := rand.Intn(100)

// Random dice roll (1 to 6)
dice := rand.Intn(6) + 1

Random Float (0.0 to 1.0)

// Random decimal between 0 and 1
fraction := rand.Float64()  // 0.234567...

Random in a Range

Want a number between 50 and 100?

min := 50
max := 100
num := rand.Intn(max-min+1) + min
graph TD A["Want 50-100"] --> B["Calculate range: 51"] B --> C["rand.Intn 51 gives 0-50"] C --> D["Add 50"] D --> E["Result: 50-100!"]

🔀 Shuffling Things

Want to mix up a list? Like shuffling cards!

cards := []string{"A", "2", "3", "4", "5"}
rand.Shuffle(len(cards), func(i, j int) {
    cards[i], cards[j] = cards[j], cards[i]
})
// Now cards are in random order!

🎰 Picking Random Items

colors := []string{"red", "blue", "green"}
picked := colors[rand.Intn(len(colors))]
// picked is a random color!

🆕 Go 1.20+ Modern Random

Go got even better! Now you can create your own random source:

// Create a new random source
r := rand.New(rand.NewSource(time.Now().UnixNano()))

// Use it
num := r.Intn(100)

This is helpful when you want different random streams that don’t interfere with each other!


🎮 Putting It All Together

Here’s a mini game: Guess the number!

package main

import (
    "fmt"
    "math"
    "math/rand"
)

func main() {
    secret := rand.Intn(10) + 1  // 1-10
    guess := 7

    diff := math.Abs(float64(secret - guess))

    if diff == 0 {
        fmt.Println("Perfect guess!")
    } else if diff <= 2 {
        fmt.Println("So close!")
    } else {
        fmt.Println("Keep trying!")
    }
}

🌟 Quick Summary

What You Want How To Get It
Absolute value math.Abs(x)
Round down math.Floor(x)
Round up math.Ceil(x)
Regular round math.Round(x)
Bigger of two math.Max(a, b)
Smaller of two math.Min(a, b)
Power math.Pow(base, exp)
Square root math.Sqrt(x)
Random 0 to n-1 rand.Intn(n)
Random 0.0 to 1.0 rand.Float64()
Shuffle slice rand.Shuffle(...)

đź’ˇ Remember!

  1. 📦 Import math for calculations, math/rand for randomness
  2. 🌱 Seed your random (or use Go 1.20+ for auto-seeding)
  3. 🎯 Intn(n) gives you 0 to n-1, so add 1 if you need 1 to n
  4. đź§® Abs makes negatives positive
  5. ⬇️⬆️ Floor goes down, Ceil goes up

Now you have the keys to Go’s math kingdom! Go calculate something awesome! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.