Ruby 4.1.0dev (2026-11-25 revision 0988275a9ba09081fff4e51763cf8e4929ec4427)
double.c
1#include "prism/internal/double.h"
2
3#include "prism/internal/assert.h"
4#include "prism/internal/bignum.h"
5#include "prism/internal/bit.h"
6#include "prism/internal/buffer.h"
7
8#include <float.h>
9#include <stdbool.h>
10#include <stdint.h>
11#include <string.h>
12
13/* The conversion builds the bits of the result directly, so it depends on the
14 * layout of a binary64 double. */
15#if FLT_RADIX != 2 || DBL_MANT_DIG != 53 || DBL_MIN_EXP != -1021 || DBL_MAX_EXP != 1024
16#error "prism requires IEEE 754 binary64 doubles"
17#endif
18
19/* Number of stored fraction bits. Normal values have an implicit leading 1. */
20#define PM_BINARY64_FRACTION_BITS 52
21
22/* Subtract this bias from the stored exponent of a normal value to get its
23 * base-2 exponent. */
24#define PM_BINARY64_EXPONENT_BIAS 1023
25
26/* All exponent bits are set for infinity (zero fraction) and NaN (nonzero
27 * fraction). */
28#define PM_BINARY64_EXPONENT_RESERVED 0x7ff
29
30/* Packed bits of positive infinity. */
31#define PM_BINARY64_INFINITY ((uint64_t) PM_BINARY64_EXPONENT_RESERVED << PM_BINARY64_FRACTION_BITS)
32
36#define PM_DOUBLE_DIGITS 768
37
41#define PM_DOUBLE_WORDS 84
42
49#define PM_DOUBLE_EXPONENT_MAXIMUM 100000000000000000
50
51#if defined(FLT_EVAL_METHOD) && FLT_EVAL_METHOD == 0
55static const double pm_double_powers[] = {
56 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11,
57 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22
58};
59#endif
60
61/* Decoded IEEE 754 fields. The exponent holds the stored 11-bit value.
62 * The fraction excludes the implicit leading bit. */
63typedef struct {
64 uint64_t fraction;
65 int32_t exponent;
66 bool negative;
68
69static pm_binary64_t
70pm_binary64_decode(double value) {
71 uint64_t bits = pm_binary64_bits(value);
72
73 return (pm_binary64_t) {
74 .fraction = bits & ((UINT64_C(1) << PM_BINARY64_FRACTION_BITS) - 1),
75 .exponent = (int32_t) ((bits >> PM_BINARY64_FRACTION_BITS) & PM_BINARY64_EXPONENT_RESERVED),
76 .negative = (bits >> 63) != 0
77 };
78}
79
80bool
81pm_double_negative_p(double value) {
82 return pm_binary64_decode(value).negative;
83}
84
85bool
86pm_double_finite_p(double value) {
87 return pm_binary64_decode(value).exponent != PM_BINARY64_EXPONENT_RESERVED;
88}
89
93static uint64_t
94pm_double_bit_length(const pm_bignum_t *bignum) {
95 PRISM_ASSERT(bignum->length > 0);
96 return (uint64_t) (bignum->length - 1) * 32 + pm_bsrll(bignum->words[bignum->length - 1]) + 1;
97}
98
107static uint64_t
108pm_double_divide(pm_bignum_t *numerator, const pm_bignum_t *divisor, bool *inexact) {
109 uint32_t *numerator_words = numerator->words;
110 const uint32_t *divisor_words = divisor->words;
111 uint32_t numerator_length = numerator->length;
112 uint32_t divisor_length = divisor->length;
113
114 PRISM_ASSERT(divisor_length >= 2 && numerator_length >= divisor_length && (divisor_words[divisor_length - 1] >> 31) == 1);
115
116 uint64_t top = divisor_words[divisor_length - 1];
117 uint64_t next = divisor_words[divisor_length - 2];
118 uint64_t quotient = 0;
119 numerator_words[numerator_length] = 0;
120
121 for (uint32_t index = numerator_length - divisor_length + 1; index > 0; index--) {
122 uint32_t *window = numerator_words + index - 1;
123 uint64_t current = ((uint64_t) window[divisor_length] << 32) | window[divisor_length - 1];
124 uint64_t estimate = current / top;
125 uint64_t remainder = current % top;
126
127 while (estimate > UINT32_MAX || estimate * next > ((remainder << 32) | window[divisor_length - 2])) {
128 estimate--;
129 remainder += top;
130 if (remainder > UINT32_MAX) break;
131 }
132
133 /* A difference below zero wraps around, which sets its top bit. */
134 uint64_t carry = 0;
135 uint64_t borrow = 0;
136
137 for (uint32_t offset = 0; offset < divisor_length; offset++) {
138 uint64_t product = estimate * divisor_words[offset] + carry;
139 carry = product >> 32;
140
141 uint64_t difference = (uint64_t) window[offset] - (uint32_t) product - borrow;
142 window[offset] = (uint32_t) difference;
143 borrow = difference >> 63;
144 }
145
146 uint64_t difference = (uint64_t) window[divisor_length] - carry - borrow;
147 window[divisor_length] = (uint32_t) difference;
148
149 if ((difference >> 63) != 0) {
150 estimate--;
151 carry = 0;
152
153 for (uint32_t offset = 0; offset < divisor_length; offset++) {
154 uint64_t sum = (uint64_t) window[offset] + divisor_words[offset] + carry;
155 window[offset] = (uint32_t) sum;
156 carry = sum >> 32;
157 }
158
159 window[divisor_length] += (uint32_t) carry;
160 }
161
162 PRISM_ASSERT((quotient >> 32) == 0);
163 quotient = (quotient << 32) | estimate;
164 }
165
166 for (uint32_t index = 0; index < divisor_length; index++) {
167 if (numerator_words[index] != 0) {
168 *inexact = true;
169 break;
170 }
171 }
172
173 return quotient;
174}
175
182static uint64_t
183pm_binary64_round(uint64_t mantissa, int64_t exponent, bool inexact) {
184 PRISM_ASSERT(mantissa != 0);
185
186 /* Drop the bits below the 53 that a double keeps, or below the smallest
187 * subnormal if the value is that small. */
188 int64_t shift = (int64_t) pm_bsrll(mantissa) + 1 - 53;
189 if (shift < -1074 - exponent) shift = -1074 - exponent;
190
191 uint64_t bits;
192 if (shift <= 0) {
193 PRISM_ASSERT(!inexact);
194 bits = mantissa << -shift;
195 } else if (shift > 64) {
196 return 0;
197 } else {
198 uint64_t half = (uint64_t) 1 << (shift - 1);
199 uint64_t rest = mantissa & (half - 1 + half);
200 bits = shift == 64 ? 0 : mantissa >> shift;
201 if (rest > half || (rest == half && (inexact || (bits & 1)))) bits++;
202 }
203
204 /* The bits hold the significand with its implicit bit, so adding the
205 * exponent field on top makes that bit carry into it. That also moves a
206 * subnormal that rounded up into the normal range, and a significand that
207 * rounded up to 2**53 into the next binade. */
208 int64_t scale = exponent + shift;
209 if (scale > 971) return PM_BINARY64_INFINITY;
210
211 bits += (uint64_t) (scale + 1074) << PM_BINARY64_FRACTION_BITS;
212 return bits < PM_BINARY64_INFINITY ? bits : PM_BINARY64_INFINITY;
213}
214
220static uint64_t
221pm_binary64_from_decimal(const uint8_t *start, uint32_t digits, int64_t exponent, uint64_t value) {
222 uint32_t numerator_words[PM_DOUBLE_WORDS] = { 0 };
223 pm_bignum_t numerator = { .length = 0, .words = numerator_words };
224
225 if (digits <= 19) {
226 numerator_words[0] = (uint32_t) value;
227 numerator_words[1] = (uint32_t) (value >> 32);
228 numerator.length = value > UINT32_MAX ? 2 : 1;
229 } else {
230 uint32_t remaining = digits > PM_DOUBLE_DIGITS ? PM_DOUBLE_DIGITS : digits;
231 uint32_t chunk = 0;
232 uint32_t multiplier = 1;
233
234 for (const uint8_t *cursor = start; remaining > 0; cursor++) {
235 if (*cursor < '0' || *cursor > '9') continue;
236
237 chunk = chunk * 10 + (uint32_t) (*cursor - '0');
238 multiplier *= 10;
239 remaining--;
240
241 if (multiplier == 1000000000) {
242 pm_bignum_mul_add(&numerator, multiplier, chunk);
243 chunk = 0;
244 multiplier = 1;
245 }
246 }
247
248 if (digits > PM_DOUBLE_DIGITS) {
249 chunk = chunk * 10 + 1;
250 multiplier *= 10;
251 exponent += (int64_t) (digits - PM_DOUBLE_DIGITS) - 1;
252 }
253
254 if (multiplier > 1) pm_bignum_mul_add(&numerator, multiplier, chunk);
255 }
256
257 bool inexact = false;
258 uint64_t mantissa;
259 int64_t binary;
260
261 /* Since 10**exp is 5**exp * 2**exp, only the power of five needs
262 * arithmetic; the power of 2 goes into the binary exponent. */
263 if (exponent >= 0) {
264 /* Multiply by the power of five and round the top 64 bits. */
265 pm_bignum_multiply_powof5(&numerator, (uint64_t) exponent);
266
267 uint64_t length = pm_double_bit_length(&numerator);
268 binary = exponent;
269
270 if (length > 64) {
271 uint64_t dropped = length - 64;
272 inexact = pm_bignum_trailing_zeros(&numerator) < dropped;
273 pm_bignum_shift_right(&numerator, (size_t) dropped);
274 binary += (int64_t) dropped;
275 }
276
277 mantissa = pm_bignum_uint64(&numerator);
278 } else {
279 /* Divide by the power of five and round the 64-bit quotient. */
280 uint32_t denominator_words[PM_DOUBLE_WORDS];
281 pm_bignum_t denominator = { .length = 1, .words = denominator_words };
282
283 denominator_words[0] = 1;
284 pm_bignum_multiply_powof5(&denominator, (uint64_t) -exponent);
285
286 /* Shift the denominator so that its top bit is set and it has at least
287 * two words, and the numerator so that it has 63 more bits than the
288 * denominator. If the numerator is already longer than that, the
289 * denominator shifts by more whole words instead. */
290 int64_t numerator_bits = (int64_t) pm_double_bit_length(&numerator);
291 int64_t denominator_bits = (int64_t) pm_double_bit_length(&denominator);
292
293 int64_t denominator_shift = (32 - denominator_bits % 32) % 32;
294 if (denominator_bits + denominator_shift == 32) denominator_shift += 32;
295
296 int64_t numerator_shift = 63 + denominator_bits + denominator_shift - numerator_bits;
297 if (numerator_shift < 0) {
298 denominator_shift += (31 - numerator_shift) / 32 * 32;
299 numerator_shift = 63 + denominator_bits + denominator_shift - numerator_bits;
300 }
301
302 pm_bignum_shift_left(&numerator, (size_t) numerator_shift);
303 pm_bignum_shift_left(&denominator, (size_t) denominator_shift);
304 PRISM_ASSERT(numerator.length < PM_DOUBLE_WORDS && denominator.length <= PM_DOUBLE_WORDS);
305
306 mantissa = pm_double_divide(&numerator, &denominator, &inexact);
307 binary = exponent + denominator_shift - numerator_shift;
308 }
309
310 return pm_binary64_round(mantissa, binary, inexact);
311}
312
316double
317pm_double_parse(const uint8_t *start, const uint8_t *end, bool *out_of_range) {
318 *out_of_range = false;
319 if (start < end && *start == '+') start++;
320
321 const uint8_t *first = NULL;
322 const uint8_t *cursor = start;
323
324 uint32_t digits = 0;
325 uint32_t zeros = 0;
326
327 uint64_t value = 0;
328 int64_t exponent = 0;
329
330 bool fraction = false;
331 bool e = false;
332
333 for (; !e && cursor < end; cursor++) {
334 switch (*cursor) {
335 case '_':
336 break;
337 case '.':
338 fraction = true;
339 break;
340 case 'e': case 'E':
341 e = true;
342 break;
343 case '0':
344 if (fraction) exponent--;
345 if (first != NULL) zeros++;
346 break;
347 case '1': case '2': case '3': case '4': case '5':
348 case '6': case '7': case '8': case '9':
349 if (fraction) exponent--;
350 if (first == NULL) first = cursor;
351
352 digits += zeros + 1;
353 if (digits <= 19) {
354 for (; zeros > 0; zeros--) value *= 10;
355 value = value * 10 + (uint64_t) (*cursor - '0');
356 } else {
357 zeros = 0;
358 }
359 break;
360 default:
361 PRISM_ASSERT(false && "unreachable");
362 break;
363 }
364 }
365
366 exponent += (int64_t) zeros;
367 if (digits == 0) return 0.0;
368
369 if (e) {
370 bool positive = true;
371 if (cursor < end && (*cursor == '+' || *cursor == '-')) {
372 positive = *cursor == '+';
373 cursor++;
374 }
375
376 int64_t power = 0;
377 for (; cursor < end; cursor++) {
378 if (*cursor != '_' && power < PM_DOUBLE_EXPONENT_MAXIMUM) power = power * 10 + (*cursor - '0');
379 }
380
381 exponent += positive ? power : -power;
382 }
383
384 int64_t magnitude = (int64_t) digits + exponent;
385 uint64_t bits;
386
387 if (magnitude > 309) {
388 bits = PM_BINARY64_INFINITY;
389 } else if (magnitude < -323) {
390 bits = 0;
391 } else {
392 /* When the digits and the power of ten are both exactly representable,
393 * a single correctly rounded multiplication or division gives the
394 * result. When the power is too large but the digits have room, part
395 * of the power moves into the digits. This depends on the operation
396 * rounding once, to a double, rather than to a wider type first. */
397#if defined(FLT_EVAL_METHOD) && FLT_EVAL_METHOD == 0
398 if (digits <= 19 && value <= ((uint64_t) 1 << 53)) {
399 if (exponent >= -22 && exponent < 0) {
400 return (double) value / pm_double_powers[-exponent];
401 } else if (exponent >= 0 && exponent <= 22) {
402 return (double) value * pm_double_powers[exponent];
403 } else if (exponent > 22 && exponent <= 22 + 15) {
404 uint64_t scaled = value;
405 for (int64_t power = exponent; power > 22 && scaled <= ((uint64_t) 1 << 53); power--) scaled *= 10;
406 if (scaled <= ((uint64_t) 1 << 53)) return (double) scaled * 1e22;
407 }
408 }
409#endif
410
411 bits = pm_binary64_from_decimal(first, digits, exponent, value);
412 }
413
414 *out_of_range = bits == 0 || bits == PM_BINARY64_INFINITY;
415
416 double result;
417 memcpy(&result, &bits, sizeof(double));
418 return result;
419}
420
425static uint64_t
426pm_double_scaled_integer(uint64_t mantissa, int32_t binary, int32_t decimal, bool *inexact) {
427 /* At most 325 powers of five times a 56-bit mantissa, or a normalized
428 * divisor times a 64-bit quotient. Both fit comfortably in 32 words. */
429 uint32_t words[32] = { (uint32_t) mantissa, (uint32_t) (mantissa >> 32) };
430 pm_bignum_t numerator = { .length = words[1] == 0 ? 1 : 2, .words = words };
431
432 int32_t shift = binary - decimal;
433 *inexact = false;
434
435 if (decimal <= 0) {
436 pm_bignum_multiply_powof5(&numerator, (uint64_t) -decimal);
437
438 if (shift < 0) {
439 *inexact = pm_bignum_trailing_zeros(&numerator) < (uint64_t) -shift;
440 pm_bignum_shift_right(&numerator, (size_t) -shift);
441 } else {
442 pm_bignum_shift_left(&numerator, (size_t) shift);
443 }
444
445 return pm_bignum_uint64(&numerator);
446 } else {
447 uint32_t divisor_words[32] = { 1 };
448 pm_bignum_t divisor = { .length = 1, .words = divisor_words };
449 pm_bignum_multiply_powof5(&divisor, (uint64_t) decimal);
450
451 /* pm_double_divide needs a normalized divisor of at least two words. */
452 int32_t bits = (int32_t) pm_double_bit_length(&divisor);
453 int32_t normalize = bits <= 64 ? 64 - bits : (32 - bits % 32) % 32;
454
455 pm_bignum_shift_left(&divisor, (size_t) normalize);
456 pm_bignum_shift_left(&numerator, (size_t) (shift + normalize));
457 return pm_double_divide(&numerator, &divisor, inexact);
458 }
459}
460
466static uint64_t
467pm_binary64_shortest_decimal(pm_binary64_t parts, int32_t *exponent) {
468 /* Subnormals use the smallest normal exponent and have no implicit bit. */
469 int32_t biased = parts.exponent == 0 ? 1 : parts.exponent;
470 uint64_t mantissa = parts.fraction;
471 if (parts.exponent != 0) mantissa += UINT64_C(1) << PM_BINARY64_FRACTION_BITS;
472
473 /* Use quarter ulps so both midpoints are integers times 2**binary.
474 * Above the smallest normal, an exact power of two has a closer neighbor
475 * below it. Subnormals and the smallest normal have equal spacing. */
476 int32_t binary = biased - PM_BINARY64_EXPONENT_BIAS - PM_BINARY64_FRACTION_BITS - 2;
477 uint64_t center = 4 * mantissa;
478 uint64_t lower = center - (parts.exponent > 1 && parts.fraction == 0 ? 1u : 2u);
479 uint64_t upper = center + 2;
480 bool even = (mantissa & 1) == 0;
481
482 /* 78913/262144 approximates log10(2). For binary in [-1076, 969],
483 * floor(binary * 78913/262144) equals floor(log10(2**binary)). Take one
484 * extra decimal place: each quarter ulp then spans at least 10 units,
485 * and even the upper midpoint is below 100 * 2**56. */
486 int32_t product = binary * 78913;
487 int32_t decimal = (product - (product < 0 ? 262143 : 0)) / 262144 - 1;
488
489 bool lower_fraction;
490 lower = pm_double_scaled_integer(lower, binary, decimal, &lower_fraction);
491
492 bool center_fraction;
493 center = pm_double_scaled_integer(center, binary, decimal, &center_fraction);
494
495 bool upper_fraction;
496 upper = pm_double_scaled_integer(upper, binary, decimal, &upper_fraction);
497
498 if (lower_fraction || !even) lower++;
499 if (!upper_fraction && !even) upper--;
500
501 /* Keep dropping a decimal place while a multiple of ten lies in the
502 * closed integer interval. Remember the discarded part of the center
503 * so the last step can choose the nearest candidate, with even ties. */
504 uint64_t digit = 0;
505 while ((lower + 9) / 10 <= upper / 10) {
506 lower = (lower + 9) / 10;
507 upper /= 10;
508 center_fraction |= digit != 0;
509 digit = center % 10;
510 center /= 10;
511 decimal++;
512 }
513
514 if (digit > 5 || (digit == 5 && (center_fraction || (center & 1)))) center++;
515 *exponent = decimal;
516
517 if (center < lower) {
518 return lower;
519 } else if (center > upper) {
520 return upper;
521 } else {
522 return center;
523 }
524}
525
529void
530pm_double_string(pm_buffer_t *buffer, double value) {
531 pm_binary64_t parts = pm_binary64_decode(value);
532
533 if (parts.exponent == PM_BINARY64_EXPONENT_RESERVED && parts.fraction != 0) {
534 PM_BUFFER_APPEND_LITERAL(buffer, "NaN");
535 return;
536 }
537 if (parts.negative) pm_buffer_append_byte(buffer, '-');
538 if (parts.exponent == PM_BINARY64_EXPONENT_RESERVED) {
539 PM_BUFFER_APPEND_LITERAL(buffer, "Infinity");
540 return;
541 }
542 if (parts.exponent == 0 && parts.fraction == 0) {
543 PM_BUFFER_APPEND_LITERAL(buffer, "0.0");
544 return;
545 }
546
547 int32_t exponent;
548 uint64_t coefficient = pm_binary64_shortest_decimal(parts, &exponent);
549
550 char digits[17]; /* A binary64 needs at most 17 significant digits. */
551 char *end = digits + sizeof(digits);
552 char *start = end;
553
554 do {
555 PRISM_ASSERT(start > digits);
556 *--start = (char) ('0' + coefficient % 10);
557 coefficient /= 10;
558 } while (coefficient != 0);
559
560 size_t length = (size_t) (end - start);
561 int32_t point = (int32_t) length + exponent;
562
563 if (point > 0 && exponent < 0) {
564 pm_buffer_append_string(buffer, start, (size_t) point);
565 pm_buffer_append_byte(buffer, '.');
566 pm_buffer_append_string(buffer, start + point, (size_t) -exponent);
567 } else if (point > 0 && point <= DBL_DIG) {
568 pm_buffer_append_string(buffer, start, length);
569 pm_buffer_append_repeated(buffer, '0', (size_t) exponent);
570 PM_BUFFER_APPEND_LITERAL(buffer, ".0");
571 } else if (point > -4 && point <= 0) {
572 PM_BUFFER_APPEND_LITERAL(buffer, "0.");
573 pm_buffer_append_repeated(buffer, '0', (size_t) -point);
574 pm_buffer_append_string(buffer, start, length);
575 } else {
576 pm_buffer_append_byte(buffer, (uint8_t) *start);
577 pm_buffer_append_byte(buffer, '.');
578
579 if (length > 1) {
580 pm_buffer_append_string(buffer, start + 1, length - 1);
581 } else {
582 pm_buffer_append_byte(buffer, '0');
583 }
584
585 exponent = point - 1;
586 pm_buffer_append_byte(buffer, 'e');
587 pm_buffer_append_byte(buffer, exponent < 0 ? '-' : '+');
588
589 int32_t power = exponent < 0 ? -exponent : exponent;
590 if (power >= 100) pm_buffer_append_byte(buffer, (uint8_t) ('0' + power / 100));
591
592 pm_buffer_append_byte(buffer, (uint8_t) ('0' + power / 10 % 10));
593 pm_buffer_append_byte(buffer, (uint8_t) ('0' + power % 10));
594 }
595}
C99 shim for <stdbool.h>.