Golang Refresher :: math & os
The Go Standard Library
math|random :: Mathematical operations and random numbers
Basics
package main
import (
"fmt"
"math"
)
func main() {
float := 997.783
// Print Pi
fmt.Println(math.Pi)
fmt.Println(math.E)
// Floor and Ceiling
fmt.Println(math.Floor(float))
fmt.Println(math.Ceil(math.E))
// Truncate to return integer value
fmt.Printf("%.2f\n", math.Trunc(math.Pi))
// Min-Max to determin the biggest/smallest member
fmt.Println(math.Max(math.Pi, math.Ln2))
fmt.Println(math.Min(math.Pi, math.Ln2))
// Modulo - the mod operator is for floats
fmt.Println(17 % 5)
fmt.Println(math.Mod(17.0, 5.0))
// Round and RoundToEven - to closes integer
fmt.Printf("%.1f\n", math.Round(10.5))
fmt.Printf("%.1f\n", math.Round(-10.5))
fmt.Printf("%.1f\n", math.RoundToEven(10.5))
fmt.Printf("%.1f\n", math.RoundToEven(11.5))
}
go run .\main.go
3.141592653589793
2.718281828459045
997
3
3.00
3.141592653589793
0.6931471805599453
2
2
11.0
-11.0
0.0
10.0
12.0
Calculations
package main
import (
"fmt"
"math"
)
func main() {
x := 10.0
// Absolute value
fmt.Println(math.Abs(x), math.Abs(-x))
// Power (x^y) and Exp (e^x)
fmt.Println(math.Pow(x, 2.0))
fmt.Println(math.Exp(x))
// Trigonometry
fmt.Println(math.Cos(math.Pi))
fmt.Println(math.Sin(2 * math.Pi))
fmt.Println(math.Tan(math.Pi / 2))
// Square and cube roots
fmt.Println(math.Sqrt(144))
fmt.Println(math.Cbrt(125))
// Hypothenuse
fmt.Println(math.Hypot(30, 40))
}
go run .\main.go
10 10
100
22026.465794806718
-1
-2.449293598294703e-16
1.6331239353195392e+16
12
5
50
Random
Package rand implements pseudo-random number generators unsuitable for security-sensitive work.
Random numbers are generated by a Source. Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run. The default Source is safe for concurrent use by multiple goroutines, but Sources created by NewSource are not.
This package's outputs might be easily predictable regardless of how it's seeded. For random numbers suitable for security-sensitive work, see the crypto/rand package.
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
// Random seed as a starting point for the generator
rand.Seed(time.Now().UnixNano())
// Generate random integers
fmt.Println(rand.Int())
fmt.Println(rand.Intn(5))
// Generate random floats
fmt.Println(rand.Float32())
fmt.Println(rand.Float64())
// Generate random ints between a and b
const a, b = 1, 10
for i := 0; i<5; i++ {
n := a + rand.Intn(b-a+1)
fmt.Print(n, " " )
}
fmt.Println()
// Generate random uppercase character
for i := 0; i<5; i++ {
c := string('A' + rune(rand.Intn('Z'-'A'+1)))
fmt.Printf("%s", c)
}
fmt.Println()
// Permutations - randomly select from array
s := []string{"Tomcat", "Fulcrum", "Viper", "Frogfoot", "Apache", "Hind", "Bone"}
// Reorder slice randomly
indexes := rand.Perm(len(s))
fmt.Println(indexes)
// Print index in the order that was generated
for i := 0; i<len(indexes); i++ {
fmt.Println(s[indexes[i]])
}
}
go run .\main.go
7000560910936529311
2
0.5594295
0.03983504194598849
6 5 2 10 9
RVFXJ
[0 3 2 1 5 4 6]
Tomcat
Frogfoot
Viper
Fulcrum
Hind
Apache
Bone
Random Strings
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
func main() {
// Random seed as a starting point for the generator
rand.Seed(time.Now().UnixNano())
// Shuffle
const numstring = "Tomcat Fulcrum Viper Frogfoot Apache Hind Bone"
// split into array of words
words := strings.Fields(numstring)
// generate new order
rand.Shuffle(len(words), func(i,j int) {
// make words swap places
words[i], words[j] = words[j], words[i]
})
fmt.Println(words)
// Random Strings
const uppercase = "QWERTYUIOOPASDFGHJKLZXCVBNM"
const lowercase = "qwertyuiopasdfghjklzxcvbnm"
const digits = "1234567890"
const special = "!@#$%^&*()_+<>?:;/.|,']"
const allchars = uppercase + lowercase + digits + special
// Generate a 10 digit password
var sb strings.Builder
length := 10
for i := 0; i < length; i++ {
sb.WriteRune(rune(allchars[rand.Intn(len(allchars))]))
}
fmt.Println("String result: ", sb.String())
// Generate a 10 digit password that !must contain all types of characters
// Create a buffer that takes 1 random character from all sets
buf := make([]byte, length)
buf[0] = uppercase[rand.Intn(len(uppercase))]
buf[1] = lowercase[rand.Intn(len(lowercase))]
buf[2] = digits[rand.Intn(len(digits))]
buf[3] = special[rand.Intn(len(special))]
// Fill up the rest of the buffer with random `allchars`
for i := 4; i < length; i++ {
buf[i] = allchars[rand.Intn(len(allchars))]
}
// Make sure that the position of the first 4 chars is shuffled
rand.Shuffle(len(buf), func(i, j int) {
// make characters swap places
buf[i], buf[j] = buf[j], buf[i]
})
fmt.Println("String result: ", string(buf))
}
go run .\main2.go
[Viper Frogfoot Bone Hind Tomcat Fulcrum Apache]
String result: 8m8ja#$)ip
String result: ]mVm|5pPL%