-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmath.go
More file actions
54 lines (45 loc) · 809 Bytes
/
math.go
File metadata and controls
54 lines (45 loc) · 809 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package toolkit
import (
"math"
"math/rand"
"sync"
"time"
)
type randomizer struct {
sync.Mutex
r *rand.Rand
}
func (r *randomizer) Intn(limit int) int {
defer r.Unlock()
r.Lock()
return r.r.Intn(limit)
}
var (
once sync.Once
r *randomizer
)
func initRandomSource() {
once.Do(func() {
src := rand.NewSource(time.Now().UnixNano())
r = new(randomizer)
r.r = rand.New(src)
})
}
func RandInt(limit int) int {
initRandomSource()
return r.Intn(limit)
}
func RandFloat(limit int, decimal int) float64 {
flim := float64(limit)
fdec := float64(decimal)
initRandomSource()
powerLimit := int(flim * math.Pow(10, fdec))
randPower := r.Intn(powerLimit)
return float64(randPower) / math.Pow(10, fdec)
}
func Div(f1, f2 float64) float64 {
if f2 == 0 {
return 0
}
return f1 / f2
}