Repository navigation
Expand file tree
/
Copy pathunit.go
More file actions
54 lines (44 loc) · 1.43 KB
/
Copy pathunit.go
File metadata and controls
54 lines (44 loc) · 1.43 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
package quant
import "math"
// Dimension is the set of valid dimension markers. Dimensions are struct
// types, which prevents accidental types such as int from being used as a
// Quantity dimension while still allowing user-defined dimensions.
type Dimension interface {
~struct{}
}
// Unit converts values between a unit and the base unit for a dimension.
// Implement ToBase and FromBase to define a custom unit outside this package.
type Unit[D Dimension] interface {
ToBase(float64) float64
FromBase(float64) float64
Dimension() D
}
// BuiltinUnit is the concrete unit type used by quant's built-in units.
type BuiltinUnit[D Dimension] struct {
factor float64
offset float64
}
func (u BuiltinUnit[D]) ToBase(v float64) float64 {
return (v + u.offset) * u.factor
}
func (u BuiltinUnit[D]) FromBase(v float64) float64 {
return v/u.factor - u.offset
}
// Dimension identifies the dimension a built-in unit belongs to. It is part
// of Unit's method set so a unit cannot be passed to a different dimension.
func (u BuiltinUnit[D]) Dimension() D {
return *new(D)
}
type scaleUnit[D Dimension] = BuiltinUnit[D]
const (
usSurveyFootInMeters = 1200.0 / 3937.0
secondsPerDay = 24 * 60 * 60
secondsPerWeek = 7 * secondsPerDay
secondsPerYear = 365.25 * secondsPerDay
secondsPerMonth = secondsPerYear / 12
standardGravity = 9.80665
)
var (
metersPerSquareMile = 1609.344 * 1609.344
radiansPerDegree = math.Pi / 180
)