-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmath.go
More file actions
78 lines (67 loc) · 1.88 KB
/
Copy pathmath.go
File metadata and controls
78 lines (67 loc) · 1.88 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// SPDX-License-Identifier: MIT
// Derived from Rough.js 4.0.4, Copyright (c) 2019 Preet Shihn.
package rough
import (
"math"
"math/rand"
)
const twoTo31 = 2147483648.0
// jsNumberStep materializes an intermediate JavaScript Number result. Go is
// otherwise allowed to fuse adjacent floating-point operations, while the
// JavaScript evaluation model rounds after each binary operation.
//
//go:noinline
func jsNumberStep(value float64) float64 { return value }
type randomState struct {
// Rough.js stores the constructor argument as a JavaScript number and only
// applies Math.imul's ToInt32 coercion on the first deterministic draw.
// Retaining the raw value matters for truthy seeds such as 0.5, 2^32, and
// Infinity: their first draw is exactly zero, and only later draws fall
// through to Math.random.
seed float64
}
func newRandom(seed float64) *randomState {
return &randomState{seed: seed}
}
func (r *randomState) next() float64 {
if r.seed == 0 || math.IsNaN(r.seed) {
return rand.Float64()
}
seed := int32(jsToInt32(r.seed))
next := int32(uint32(seed) * uint32(48271))
r.seed = float64(next)
return float64(uint32(next)&0x7fffffff) / twoTo31
}
func jsToInt32(v float64) int64 {
if v == 0 || math.IsNaN(v) || math.IsInf(v, 0) {
return 0
}
t := math.Trunc(v)
m := math.Mod(t, 4294967296)
if m < 0 {
m += 4294967296
}
if m >= 2147483648 {
m -= 4294967296
}
return int64(m)
}
// NewSeed returns a nondeterministic seed in Rough.js's supported range.
func NewSeed() float64 {
return math.Floor(rand.Float64() * twoTo31)
}
func random(o *ResolvedOptions) float64 {
if o.randomizer == nil {
o.randomizer = newRandom(o.Seed)
}
return o.randomizer.next()
}
func jsRound(v float64) float64 {
if math.IsNaN(v) || math.IsInf(v, 0) || v == 0 || math.Abs(v) >= 1<<52 {
return v
}
if v >= -0.5 && v < 0 {
return math.Copysign(0, -1)
}
return math.Floor(v + 0.5)
}