Debian Codegraph @

include/fast_float/digit_comparison.h

raw
1 #ifndef FASTFLOAT_DIGIT_COMPARISON_H
2 #define FASTFLOAT_DIGIT_COMPARISON_H
3
4 #include <algorithm>
5 #include <cstdint>
6 #include <cstring>
7 #include <iterator>
8
9 #include "float_common.h"
10 #include "bigint.h"
11 #include "ascii_number.h"
12
13 namespace fast_float {
14
15 // 1e0 to 1e19
16 constexpr static uint64_t powers_of_ten_uint64[] = {1UL,
17 10UL,
18 100UL,
19 1000UL,
20 10000UL,
21 100000UL,
22 1000000UL,
23 10000000UL,
24 100000000UL,
25 1000000000UL,
26 10000000000UL,
27 100000000000UL,
28 1000000000000UL,
29 10000000000000UL,
30 100000000000000UL,
31 1000000000000000UL,
32 10000000000000000UL,
33 100000000000000000UL,
34 1000000000000000000UL,
35 10000000000000000000UL};
36
37 // calculate the exponent, in scientific notation, of the number.
38 // this algorithm is not even close to optimized, but it has no practical
39 // effect on performance: in order to have a faster algorithm, we'd need
40 // to slow down performance for faster algorithms, and this is still fast.
41 template <typename UC>
42 fastfloat_really_inline FASTFLOAT_CONSTEXPR14 int32_t
43 scientific_exponent(parsed_number_string_t<UC> &num) noexcept {
44 uint64_t mantissa = num.mantissa;
45 int32_t exponent = int32_t(num.exponent);
46 while (mantissa >= 10000) {
47 mantissa /= 10000;
48 exponent += 4;
49 }
50 while (mantissa >= 100) {
51 mantissa /= 100;
52 exponent += 2;
53 }
54 while (mantissa >= 10) {
55 mantissa /= 10;
56 exponent += 1;
57 }
58 return exponent;
59 }
60
61 // this converts a native floating-point number to an extended-precision float.
62 template <typename T>
63 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa
64 to_extended(T value) noexcept {
65 using equiv_uint = equiv_uint_t<T>;
66 constexpr equiv_uint exponent_mask = binary_format<T>::exponent_mask();
67 constexpr equiv_uint mantissa_mask = binary_format<T>::mantissa_mask();
68 constexpr equiv_uint hidden_bit_mask = binary_format<T>::hidden_bit_mask();
69
70 adjusted_mantissa am;
71 int32_t bias = binary_format<T>::mantissa_explicit_bits() -
72 binary_format<T>::minimum_exponent();
73 equiv_uint bits;
74 #if FASTFLOAT_HAS_BIT_CAST
75 bits = std::bit_cast<equiv_uint>(value);
76 #else
77 ::memcpy(&bits, &value, sizeof(T));
78 #endif
79 if ((bits & exponent_mask) == 0) {
80 // denormal
81 am.power2 = 1 - bias;
82 am.mantissa = bits & mantissa_mask;
83 } else {
84 // normal
85 am.power2 = int32_t((bits & exponent_mask) >>
86 binary_format<T>::mantissa_explicit_bits());
87 am.power2 -= bias;
88 am.mantissa = (bits & mantissa_mask) | hidden_bit_mask;
89 }
90
91 return am;
92 }
93
94 // get the extended precision value of the halfway point between b and b+u.
95 // we are given a native float that represents b, so we need to adjust it
96 // halfway between b and b+u.
97 template <typename T>
98 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa
99 to_extended_halfway(T value) noexcept {
100 adjusted_mantissa am = to_extended(value);
101 am.mantissa <<= 1;
102 am.mantissa += 1;
103 am.power2 -= 1;
104 return am;
105 }
106
107 // round an extended-precision float to the nearest machine float.
108 template <typename T, typename callback>
109 fastfloat_really_inline FASTFLOAT_CONSTEXPR14 void round(adjusted_mantissa &am,
110 callback cb) noexcept {
111 int32_t mantissa_shift = 64 - binary_format<T>::mantissa_explicit_bits() - 1;
112 if (-am.power2 >= mantissa_shift) {
113 // have a denormal float
114 int32_t shift = -am.power2 + 1;
115 cb(am, std::min<int32_t>(shift, 64));
116 // check for round-up: if rounding-nearest carried us to the hidden bit.
117 am.power2 = (am.mantissa <
118 (uint64_t(1) << binary_format<T>::mantissa_explicit_bits()))
119 ? 0
120 : 1;
121 return;
122 }
123
124 // have a normal float, use the default shift.
125 cb(am, mantissa_shift);
126
127 // check for carry
128 if (am.mantissa >=
129 (uint64_t(2) << binary_format<T>::mantissa_explicit_bits())) {
130 am.mantissa = (uint64_t(1) << binary_format<T>::mantissa_explicit_bits());
131 am.power2++;
132 }
133
134 // check for infinite: we could have carried to an infinite power
135 am.mantissa &= ~(uint64_t(1) << binary_format<T>::mantissa_explicit_bits());
136 if (am.power2 >= binary_format<T>::infinite_power()) {
137 am.power2 = binary_format<T>::infinite_power();
138 am.mantissa = 0;
139 }
140 }
141
142 template <typename callback>
143 fastfloat_really_inline FASTFLOAT_CONSTEXPR14 void
144 round_nearest_tie_even(adjusted_mantissa &am, int32_t shift,
145 callback cb) noexcept {
146 uint64_t const mask = (shift == 64) ? UINT64_MAX : (uint64_t(1) << shift) - 1;
147 uint64_t const halfway = (shift == 0) ? 0 : uint64_t(1) << (shift - 1);
148 uint64_t truncated_bits = am.mantissa & mask;
149 bool is_above = truncated_bits > halfway;
150 bool is_halfway = truncated_bits == halfway;
151
152 // shift digits into position
153 if (shift == 64) {
154 am.mantissa = 0;
155 } else {
156 am.mantissa >>= shift;
157 }
158 am.power2 += shift;
159
160 bool is_odd = (am.mantissa & 1) == 1;
161 am.mantissa += uint64_t(cb(is_odd, is_halfway, is_above));
162 }
163
164 fastfloat_really_inline FASTFLOAT_CONSTEXPR14 void
165 round_down(adjusted_mantissa &am, int32_t shift) noexcept {
166 if (shift == 64) {
167 am.mantissa = 0;
168 } else {
169 am.mantissa >>= shift;
170 }
171 am.power2 += shift;
172 }
173
174 template <typename UC>
175 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void
176 skip_zeros(UC const *&first, UC const *last) noexcept {
177 uint64_t val;
178 while (!cpp20_and_in_constexpr() &&
179 std::distance(first, last) >= int_cmp_len<UC>()) {
180 ::memcpy(&val, first, sizeof(uint64_t));
181 if (val != int_cmp_zeros<UC>()) {
182 break;
183 }
184 first += int_cmp_len<UC>();
185 }
186 while (first != last) {
187 if (*first != UC('0')) {
188 break;
189 }
190 first++;
191 }
192 }
193
194 // determine if any non-zero digits were truncated.
195 // all characters must be valid digits.
196 template <typename UC>
197 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool
198 is_truncated(UC const *first, UC const *last) noexcept {
199 // do 8-bit optimizations, can just compare to 8 literal 0s.
200 uint64_t val;
201 while (!cpp20_and_in_constexpr() &&
202 std::distance(first, last) >= int_cmp_len<UC>()) {
203 ::memcpy(&val, first, sizeof(uint64_t));
204 if (val != int_cmp_zeros<UC>()) {
205 return true;
206 }
207 first += int_cmp_len<UC>();
208 }
209 while (first != last) {
210 if (*first != UC('0')) {
211 return true;
212 }
213 ++first;
214 }
215 return false;
216 }
217
218 template <typename UC>
219 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool
220 is_truncated(span<UC const> s) noexcept {
221 return is_truncated(s.ptr, s.ptr + s.len());
222 }
223
224 template <typename UC>
225 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void
226 parse_eight_digits(UC const *&p, limb &value, size_t &counter,
227 size_t &count) noexcept {
228 value = value * 100000000 + parse_eight_digits_unrolled(p);
229 p += 8;
230 counter += 8;
231 count += 8;
232 }
233
234 template <typename UC>
235 fastfloat_really_inline FASTFLOAT_CONSTEXPR14 void
236 parse_one_digit(UC const *&p, limb &value, size_t &counter,
237 size_t &count) noexcept {
238 value = value * 10 + limb(*p - UC('0'));
239 p++;
240 counter++;
241 count++;
242 }
243
244 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void
245 add_native(bigint &big, limb power, limb value) noexcept {
246 big.mul(power);
247 big.add(value);
248 }
249
250 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void
251 round_up_bigint(bigint &big, size_t &count) noexcept {
252 // need to round-up the digits, but need to avoid rounding
253 // ....9999 to ...10000, which could cause a false halfway point.
254 add_native(big, 10, 1);
255 count++;
256 }
257
258 // parse the significant digits into a big integer
259 template <typename UC>
260 inline FASTFLOAT_CONSTEXPR20 void
261 parse_mantissa(bigint &result, parsed_number_string_t<UC> &num,
262 size_t max_digits, size_t &digits) noexcept {
263 // try to minimize the number of big integer and scalar multiplication.
264 // therefore, try to parse 8 digits at a time, and multiply by the largest
265 // scalar value (9 or 19 digits) for each step.
266 size_t counter = 0;
267 digits = 0;
268 limb value = 0;
269 #ifdef FASTFLOAT_64BIT_LIMB
270 size_t step = 19;
271 #else
272 size_t step = 9;
273 #endif
274
275 // process all integer digits.
276 UC const *p = num.integer.ptr;
277 UC const *pend = p + num.integer.len();
278 skip_zeros(p, pend);
279 // process all digits, in increments of step per loop
280 while (p != pend) {
281 while ((std::distance(p, pend) >= 8) && (step - counter >= 8) &&
282 (max_digits - digits >= 8)) {
283 parse_eight_digits(p, value, counter, digits);
284 }
285 while (counter < step && p != pend && digits < max_digits) {
286 parse_one_digit(p, value, counter, digits);
287 }
288 if (digits == max_digits) {
289 // add the temporary value, then check if we've truncated any digits
290 add_native(result, limb(powers_of_ten_uint64[counter]), value);
291 bool truncated = is_truncated(p, pend);
292 if (num.fraction.ptr != nullptr) {
293 truncated |= is_truncated(num.fraction);
294 }
295 if (truncated) {
296 round_up_bigint(result, digits);
297 }
298 return;
299 } else {
300 add_native(result, limb(powers_of_ten_uint64[counter]), value);
301 counter = 0;
302 value = 0;
303 }
304 }
305
306 // add our fraction digits, if they're available.
307 if (num.fraction.ptr != nullptr) {
308 p = num.fraction.ptr;
309 pend = p + num.fraction.len();
310 if (digits == 0) {
311 skip_zeros(p, pend);
312 }
313 // process all digits, in increments of step per loop
314 while (p != pend) {
315 while ((std::distance(p, pend) >= 8) && (step - counter >= 8) &&
316 (max_digits - digits >= 8)) {
317 parse_eight_digits(p, value, counter, digits);
318 }
319 while (counter < step && p != pend && digits < max_digits) {
320 parse_one_digit(p, value, counter, digits);
321 }
322 if (digits == max_digits) {
323 // add the temporary value, then check if we've truncated any digits
324 add_native(result, limb(powers_of_ten_uint64[counter]), value);
325 bool truncated = is_truncated(p, pend);
326 if (truncated) {
327 round_up_bigint(result, digits);
328 }
329 return;
330 } else {
331 add_native(result, limb(powers_of_ten_uint64[counter]), value);
332 counter = 0;
333 value = 0;
334 }
335 }
336 }
337
338 if (counter != 0) {
339 add_native(result, limb(powers_of_ten_uint64[counter]), value);
340 }
341 }
342
343 template <typename T>
344 inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa
345 positive_digit_comp(bigint &bigmant, int32_t exponent) noexcept {
346 FASTFLOAT_ASSERT(bigmant.pow10(uint32_t(exponent)));
347 adjusted_mantissa answer;
348 bool truncated;
349 answer.mantissa = bigmant.hi64(truncated);
350 int bias = binary_format<T>::mantissa_explicit_bits() -
351 binary_format<T>::minimum_exponent();
352 answer.power2 = bigmant.bit_length() - 64 + bias;
353
354 round<T>(answer, [truncated](adjusted_mantissa &a, int32_t shift) {
355 round_nearest_tie_even(
356 a, shift,
357 [truncated](bool is_odd, bool is_halfway, bool is_above) -> bool {
358 return is_above || (is_halfway && truncated) ||
359 (is_odd && is_halfway);
360 });
361 });
362
363 return answer;
364 }
365
366 // the scaling here is quite simple: we have, for the real digits `m * 10^e`,
367 // and for the theoretical digits `n * 2^f`. Since `e` is always negative,
368 // to scale them identically, we do `n * 2^f * 5^-f`, so we now have `m * 2^e`.
369 // we then need to scale by `2^(f- e)`, and then the two significant digits
370 // are of the same magnitude.
371 template <typename T>
372 inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa negative_digit_comp(
373 bigint &bigmant, adjusted_mantissa am, int32_t exponent) noexcept {
374 bigint &real_digits = bigmant;
375 int32_t real_exp = exponent;
376
377 // get the value of `b`, rounded down, and get a bigint representation of b+h
378 adjusted_mantissa am_b = am;
379 // gcc7 buf: use a lambda to remove the noexcept qualifier bug with
380 // -Wnoexcept-type.
381 round<T>(am_b,
382 [](adjusted_mantissa &a, int32_t shift) { round_down(a, shift); });
383 T b;
384 to_float(false, am_b, b);
385 adjusted_mantissa theor = to_extended_halfway(b);
386 bigint theor_digits(theor.mantissa);
387 int32_t theor_exp = theor.power2;
388
389 // scale real digits and theor digits to be same power.
390 int32_t pow2_exp = theor_exp - real_exp;
391 uint32_t pow5_exp = uint32_t(-real_exp);
392 if (pow5_exp != 0) {
393 FASTFLOAT_ASSERT(theor_digits.pow5(pow5_exp));
394 }
395 if (pow2_exp > 0) {
396 FASTFLOAT_ASSERT(theor_digits.pow2(uint32_t(pow2_exp)));
397 } else if (pow2_exp < 0) {
398 FASTFLOAT_ASSERT(real_digits.pow2(uint32_t(-pow2_exp)));
399 }
400
401 // compare digits, and use it to director rounding
402 int ord = real_digits.compare(theor_digits);
403 adjusted_mantissa answer = am;
404 round<T>(answer, [ord](adjusted_mantissa &a, int32_t shift) {
405 round_nearest_tie_even(
406 a, shift, [ord](bool is_odd, bool _, bool __) -> bool {
407 (void)_; // not needed, since we've done our comparison
408 (void)__; // not needed, since we've done our comparison
409 if (ord > 0) {
410 return true;
411 } else if (ord < 0) {
412 return false;
413 } else {
414 return is_odd;
415 }
416 });
417 });
418
419 return answer;
420 }
421
422 // parse the significant digits as a big integer to unambiguously round the
423 // the significant digits. here, we are trying to determine how to round
424 // an extended float representation close to `b+h`, halfway between `b`
425 // (the float rounded-down) and `b+u`, the next positive float. this
426 // algorithm is always correct, and uses one of two approaches. when
427 // the exponent is positive relative to the significant digits (such as
428 // 1234), we create a big-integer representation, get the high 64-bits,
429 // determine if any lower bits are truncated, and use that to direct
430 // rounding. in case of a negative exponent relative to the significant
431 // digits (such as 1.2345), we create a theoretical representation of
432 // `b` as a big-integer type, scaled to the same binary exponent as
433 // the actual digits. we then compare the big integer representations
434 // of both, and use that to direct rounding.
435 template <typename T, typename UC>
436 inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa
437 digit_comp(parsed_number_string_t<UC> &num, adjusted_mantissa am) noexcept {
438 // remove the invalid exponent bias
439 am.power2 -= invalid_am_bias;
440
441 int32_t sci_exp = scientific_exponent(num);
442 size_t max_digits = binary_format<T>::max_digits();
443 size_t digits = 0;
444 bigint bigmant;
445 parse_mantissa(bigmant, num, max_digits, digits);
446 // can't underflow, since digits is at most max_digits.
447 int32_t exponent = sci_exp + 1 - int32_t(digits);
448 if (exponent >= 0) {
449 return positive_digit_comp<T>(bigmant, exponent);
450 } else {
451 return negative_digit_comp<T>(bigmant, am, exponent);
452 }
453 }
454
455 } // namespace fast_float
456
457 #endif