...
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 x == 0 || IsNaN(x) || IsInf(x, 0) {
70 return x
71 }
72 d, _ := Modf(x)
73 return d
74 }
75
76
77
78
79
80
81
82
83 func Round(x float64) float64 {
84
85
86
87
88
89
90
91
92
93 bits := Float64bits(x)
94 e := uint(bits>>shift) & mask
95 if e < bias {
96
97 bits &= signMask
98 if e == bias-1 {
99 bits |= uvone
100 }
101 } else if e < bias+shift {
102
103
104
105
106 const half = 1 << (shift - 1)
107 e -= bias
108 bits += half >> e
109 bits &^= fracMask >> e
110 }
111 return Float64frombits(bits)
112 }
113
114
115
116
117
118
119
120
121 func RoundToEven(x float64) float64 {
122
123
124
125
126
127
128
129
130
131
132 bits := Float64bits(x)
133 e := uint(bits>>shift) & mask
134 if e >= bias {
135
136
137
138
139 const halfMinusULP = (1 << (shift - 1)) - 1
140 e -= bias
141 bits += (halfMinusULP + (bits>>(shift-e))&1) >> e
142 bits &^= fracMask >> e
143 } else if e == bias-1 && bits&fracMask != 0 {
144
145 bits = bits&signMask | uvone
146 } else {
147
148 bits &= signMask
149 }
150 return Float64frombits(bits)
151 }
152
View as plain text