...
Source file
src/math/floor.go
Documentation: math
1
2
3
4
5 package math
6
7
8
9
10
11
12
13 func Floor(x float64) float64 {
14 if haveArchFloor {
15 return archFloor(x)
16 }
17 return floor(x)
18 }
19
20 func floor(x float64) float64 {
21 if x == 0 || IsNaN(x) || IsInf(x, 0) {
22 return x
23 }
24 if x < 0 {
25 d, fract := Modf(-x)
26 if fract != 0.0 {
27 d = d + 1
28 }
29 return -d
30 }
31 d, _ := Modf(x)
32 return d
33 }
34
35
36
37
38
39
40
41 func Ceil(x float64) float64 {
42 if haveArchCeil {
43 return archCeil(x)
44 }
45 return ceil(x)
46 }
47
48 func ceil(x float64) float64 {
49 return -Floor(-x)
50 }
51
52
53
54
55
56
57
58 func Trunc(x float64) float64 {
59 if haveArchTrunc {
60 return archTrunc(x)
61 }
62 return trunc(x)
63 }
64
65 func trunc(x float64) float64 {
66 if x == 0 || IsNaN(x) || IsInf(x, 0) {
67 return x
68 }
69 d, _ := Modf(x)
70 return d
71 }
72
73
74
75
76
77
78
79 func Round(x float64) float64 {
80
81
82
83
84
85
86
87
88
89 bits := Float64bits(x)
90 e := uint(bits>>shift) & mask
91 if e < bias {
92
93 bits &= signMask
94 if e == bias-1 {
95 bits |= uvone
96 }
97 } else if e < bias+shift {
98
99
100
101
102 const half = 1 << (shift - 1)
103 e -= bias
104 bits += half >> e
105 bits &^= fracMask >> e
106 }
107 return Float64frombits(bits)
108 }
109
110
111
112
113
114
115
116 func RoundToEven(x float64) float64 {
117
118
119
120
121
122
123
124
125
126
127 bits := Float64bits(x)
128 e := uint(bits>>shift) & mask
129 if e >= bias {
130
131
132
133
134 const halfMinusULP = (1 << (shift - 1)) - 1
135 e -= bias
136 bits += (halfMinusULP + (bits>>(shift-e))&1) >> e
137 bits &^= fracMask >> e
138 } else if e == bias-1 && bits&fracMask != 0 {
139
140 bits = bits&signMask | uvone
141 } else {
142
143 bits &= signMask
144 }
145 return Float64frombits(bits)
146 }
147
View as plain text