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