| 14593 | */ |
| 14594 | template<typename FloatType> |
| 14595 | boundaries compute_boundaries(FloatType value) |
| 14596 | { |
| 14597 | JSON_ASSERT(std::isfinite(value)); |
| 14598 | JSON_ASSERT(value > 0); |
| 14599 | |
| 14600 | // Convert the IEEE representation into a diyfp. |
| 14601 | // |
| 14602 | // If v is denormal: |
| 14603 | // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) |
| 14604 | // If v is normalized: |
| 14605 | // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) |
| 14606 | |
| 14607 | static_assert(std::numeric_limits<FloatType>::is_iec559, |
| 14608 | "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); |
| 14609 | |
| 14610 | constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit) |
| 14611 | constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1); |
| 14612 | constexpr int kMinExp = 1 - kBias; |
| 14613 | constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) |
| 14614 | |
| 14615 | using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type; |
| 14616 | |
| 14617 | const std::uint64_t bits = reinterpret_bits<bits_type>(value); |
| 14618 | const std::uint64_t E = bits >> (kPrecision - 1); |
| 14619 | const std::uint64_t F = bits & (kHiddenBit - 1); |
| 14620 | |
| 14621 | const bool is_denormal = E == 0; |
| 14622 | const diyfp v = is_denormal |
| 14623 | ? diyfp(F, kMinExp) |
| 14624 | : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias); |
| 14625 | |
| 14626 | // Compute the boundaries m- and m+ of the floating-point value |
| 14627 | // v = f * 2^e. |
| 14628 | // |
| 14629 | // Determine v- and v+, the floating-point predecessor and successor if v, |
| 14630 | // respectively. |
| 14631 | // |
| 14632 | // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) |
| 14633 | // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) |
| 14634 | // |
| 14635 | // v+ = v + 2^e |
| 14636 | // |
| 14637 | // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ |
| 14638 | // between m- and m+ round to v, regardless of how the input rounding |
| 14639 | // algorithm breaks ties. |
| 14640 | // |
| 14641 | // ---+-------------+-------------+-------------+-------------+--- (A) |
| 14642 | // v- m- v m+ v+ |
| 14643 | // |
| 14644 | // -----------------+------+------+-------------+-------------+--- (B) |
| 14645 | // v- m- v m+ v+ |
| 14646 | |
| 14647 | const bool lower_boundary_is_closer = F == 0 && E > 1; |
| 14648 | const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); |
| 14649 | const diyfp m_minus = lower_boundary_is_closer |
| 14650 | ? diyfp(4 * v.f - 1, v.e - 2) // (B) |
| 14651 | : diyfp(2 * v.f - 1, v.e - 1); // (A) |
| 14652 | |