| 12829 | */ |
| 12830 | template <typename FloatType> |
| 12831 | boundaries compute_boundaries(FloatType value) |
| 12832 | { |
| 12833 | assert(std::isfinite(value)); |
| 12834 | assert(value > 0); |
| 12835 | |
| 12836 | // Convert the IEEE representation into a diyfp. |
| 12837 | // |
| 12838 | // If v is denormal: |
| 12839 | // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) |
| 12840 | // If v is normalized: |
| 12841 | // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) |
| 12842 | |
| 12843 | static_assert(std::numeric_limits<FloatType>::is_iec559, |
| 12844 | "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); |
| 12845 | |
| 12846 | constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit) |
| 12847 | constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1); |
| 12848 | constexpr int kMinExp = 1 - kBias; |
| 12849 | constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) |
| 12850 | |
| 12851 | using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type; |
| 12852 | |
| 12853 | const std::uint64_t bits = reinterpret_bits<bits_type>(value); |
| 12854 | const std::uint64_t E = bits >> (kPrecision - 1); |
| 12855 | const std::uint64_t F = bits & (kHiddenBit - 1); |
| 12856 | |
| 12857 | const bool is_denormal = E == 0; |
| 12858 | const diyfp v = is_denormal |
| 12859 | ? diyfp(F, kMinExp) |
| 12860 | : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias); |
| 12861 | |
| 12862 | // Compute the boundaries m- and m+ of the floating-point value |
| 12863 | // v = f * 2^e. |
| 12864 | // |
| 12865 | // Determine v- and v+, the floating-point predecessor and successor if v, |
| 12866 | // respectively. |
| 12867 | // |
| 12868 | // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) |
| 12869 | // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) |
| 12870 | // |
| 12871 | // v+ = v + 2^e |
| 12872 | // |
| 12873 | // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ |
| 12874 | // between m- and m+ round to v, regardless of how the input rounding |
| 12875 | // algorithm breaks ties. |
| 12876 | // |
| 12877 | // ---+-------------+-------------+-------------+-------------+--- (A) |
| 12878 | // v- m- v m+ v+ |
| 12879 | // |
| 12880 | // -----------------+------+------+-------------+-------------+--- (B) |
| 12881 | // v- m- v m+ v+ |
| 12882 | |
| 12883 | const bool lower_boundary_is_closer = F == 0 and E > 1; |
| 12884 | const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); |
| 12885 | const diyfp m_minus = lower_boundary_is_closer |
| 12886 | ? diyfp(4 * v.f - 1, v.e - 2) // (B) |
| 12887 | : diyfp(2 * v.f - 1, v.e - 1); // (A) |
| 12888 | |