From 12a1ca584696c38e1407e5d89e38f59225af01f2 Mon Sep 17 00:00:00 2001 From: Niels Lohmann Date: Wed, 25 Nov 2026 22:25:24 +0100 Subject: [PATCH] Write floats with the shortest digits (Zmij for binary32) The conversion of Zmij becomes a template on the bit layout of the format, as upstream Zmij does, and floats (IEEE 754 binary32) use it instead of Grisu2. The layout of the text (format_buffer()) stays the same; only the digits change, for 8,821,575 of the 2,139,095,039 positive finite floats: 4,627,275 get one digit fewer (Grisu2 leaves out decimals on the boundary of the rounding interval), and 4,194,300 take the even one of two equally close decimals. Every float still reads back as itself. The conversion of doubles compiles to the same code as before. Signed-off-by: Niels Lohmann --- .../docs/features/types/number_handling.md | 3 +- .../features/types/template_parameters.md | 9 +- docs/mkdocs/docs/home/license.md | 2 +- .../nlohmann/detail/conversions/to_chars.hpp | 86 ++++++++++-- include/nlohmann/detail/conversions/zmij.hpp | 41 ++++-- single_include/nlohmann/json.hpp | 127 ++++++++++++++--- tests/src/unit-to_chars.cpp | 131 +++++++++++++++++- 7 files changed, 344 insertions(+), 55 deletions(-) diff --git a/docs/mkdocs/docs/features/types/number_handling.md b/docs/mkdocs/docs/features/types/number_handling.md index 82bbe1824..4405cfb16 100644 --- a/docs/mkdocs/docs/features/types/number_handling.md +++ b/docs/mkdocs/docs/features/types/number_handling.md @@ -168,8 +168,7 @@ library; pick one or type it to see the row): - Integer numbers are serialized as is; that is, no scientific notation is used. - Floating-point numbers are serialized with the fewest digits that read back as the same value (the closest such digits if there are several), in the layout of the `#!c %g` printf modifier: `#!c 1.5`, `#!c 100.0`, `#!c 1e+100`. - Doubles are converted with the algorithm of [Żmij](https://github.com/vitaut/zmij), floats with Grisu2, which - can write more digits than necessary. + Doubles and floats are converted with the algorithm of [Żmij](https://github.com/vitaut/zmij). !!! hint "Notes regarding precision of floating-point numbers" diff --git a/docs/mkdocs/docs/features/types/template_parameters.md b/docs/mkdocs/docs/features/types/template_parameters.md index 6a09fbeef..7175ce54b 100644 --- a/docs/mkdocs/docs/features/types/template_parameters.md +++ b/docs/mkdocs/docs/features/types/template_parameters.md @@ -575,10 +575,9 @@ therefore silently changes parse results rather than raising an error. See specifiers, for which the library likewise provides only `#!cpp double` and `#!cpp long double` overloads (`#!cpp float` is promoted to `#!cpp double`). -If `#!cpp std::numeric_limits` describes an IEEE 754 binary64 number, `dump` uses the algorithm of -Żmij, which produces the shortest representation that round-trips. For IEEE 754 binary32 numbers, it uses Grisu2, -which produces a short representation that round-trips. Otherwise the `snprintf` fallback with `max_digits10` digits is -used. +If `#!cpp std::numeric_limits` describes an IEEE 754 binary64 or binary32 number, `dump` uses the +algorithm of Żmij, which produces the shortest representation that round-trips. Otherwise the `snprintf` fallback with +`max_digits10` digits is used. ### Required for the binary formats @@ -591,7 +590,7 @@ binary32 or binary64 field and have no encoding for `#!cpp long double`. | Type | Support | |--------------------------|-----------------------------------------------------------------------------------------------------------------------| | `#!cpp double` (default) | full; shortest round-trip output through Żmij | -| `#!cpp float` | full; short round-trip output through Grisu2 | +| `#!cpp float` | full; shortest round-trip output through Żmij | | `#!cpp long double` | `dump` and `parse` only; the binary format writers do not compile, as they only handle IEEE 754 binary32 and binary64 | | any other type | not usable | diff --git a/docs/mkdocs/docs/home/license.md b/docs/mkdocs/docs/home/license.md index c0bb94633..9376c028d 100644 --- a/docs/mkdocs/docs/home/license.md +++ b/docs/mkdocs/docs/home/license.md @@ -18,7 +18,7 @@ The class contains the UTF-8 Decoder from Bjoern Hoehrmann which is licensed und The class contains a slightly modified version of the Grisu2 algorithm from Florian Loitsch which is licensed under the [MIT License](https://opensource.org/licenses/MIT) (see above). Copyright © 2009 [Florian Loitsch](https://florian.loitsch.com/) -The class contains a port of the shortest double-to-decimal conversion of [Żmij](https://github.com/vitaut/zmij) by Victor Zverovich, including the conversion of the digits to text by Xiang JunBo and the SIMD instruction sequence of Dougall Johnson, which is licensed under the [MIT License](https://opensource.org/licenses/MIT) (see above). Copyright © 2025 [Victor Zverovich](https://github.com/vitaut) +The class contains a port of the shortest double- and float-to-decimal conversion of [Żmij](https://github.com/vitaut/zmij) by Victor Zverovich, including the conversion of the digits to text by Xiang JunBo and the SIMD instruction sequence of Dougall Johnson, which is licensed under the [MIT License](https://opensource.org/licenses/MIT) (see above). Copyright © 2025 [Victor Zverovich](https://github.com/vitaut) The class contains a copy of [Hedley](https://nemequ.github.io/hedley/) from Evan Nemerson which is licensed as [CC0-1.0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/include/nlohmann/detail/conversions/to_chars.hpp b/include/nlohmann/detail/conversions/to_chars.hpp index 67a708f62..8d9cc6947 100644 --- a/include/nlohmann/detail/conversions/to_chars.hpp +++ b/include/nlohmann/detail/conversions/to_chars.hpp @@ -49,8 +49,8 @@ namespace detail /*! @brief implements binary to decimal floating-point conversion: the shortest -digits of Zmij (see zmij.hpp) for IEEE 754 binary64 numbers, and the Grisu2 -algorithm for all other formats. +digits of Zmij (see zmij.hpp) for IEEE 754 binary64 and binary32 numbers, and +the Grisu2 algorithm for all other formats. The Grisu2 implementation is a slightly modified version of the reference implementation which may be obtained from @@ -1397,8 +1397,9 @@ inline char* write_short_decimal(char* first, std::uint64_t digits, int exp) noe @brief whether FloatType is an IEEE 754 binary64 type (a double, or a long double that has the same format, as with MSVC and on Apple's Arm CPUs) -These are the types the conversion of Zmij (see zmij.hpp) is used for; all -others (binary32, or a format the library does not know) use Grisu2. +These are the types the conversion of Zmij (see zmij.hpp) is used for with +write_shortest(); binary32 numbers use it with format_buffer(), and all +others (e.g. the 80-bit long double of x87) use Grisu2. */ template constexpr bool has_binary64_format() noexcept @@ -1412,7 +1413,23 @@ constexpr bool has_binary64_format() noexcept template struct is_binary64 : std::integral_constant()> {}; -/// a positive finite float (other than binary64): Grisu2 and format_buffer() +/// whether FloatType is an IEEE 754 binary32 type (a float); these use the +/// conversion of Zmij as well +template +constexpr bool has_binary32_format() noexcept +{ + return std::numeric_limits::is_iec559 + && std::numeric_limits::digits == 24 + && std::numeric_limits::max_exponent == 128 + && sizeof(FloatType) == sizeof(std::uint32_t); +} + +/// the conversion for a floating-point type: 0 for Grisu2, 1 for Zmij on +/// binary64, 2 for Zmij on binary32 +template +struct float_conversion : std::integral_constant < int, (has_binary64_format() ? 1 : 0) + (has_binary32_format() ? 2 : 0) > {}; + +/// a positive finite float (other than binary64 and binary32): Grisu2 and format_buffer() template JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_RETURNS_NON_NULL @@ -1466,32 +1483,79 @@ char* write_positive_zmij(char* first, const char* last, FloatType value) return first + len; } +/// a positive finite binary32 number: the shortest digits (Zmij), laid out by +/// format_buffer() as the digits of Grisu2 were (only the digits differ: Grisu2 +/// leaves out a decimal on the boundary of the rounding interval and may take +/// the other one of two equally close decimals) +template +JSON_HEDLEY_NON_NULL(1, 2) +JSON_HEDLEY_RETURNS_NON_NULL +char* write_positive_zmij_binary32(char* first, const char* last, FloatType value) +{ + static_assert(has_binary32_format(), + "internal error: this conversion of Zmij needs IEEE 754 binary32 numbers"); + const zmij::shortest_decimal d = zmij::to_shortest_of(bit_cast(value)); + std::uint64_t digits = d.has_digit ? (d.integral * 10) + d.digit : d.integral; + int decimal_exponent = d.has_digit ? d.exponent : d.exponent + 1; + while (digits % 10 == 0) + { + digits /= 10; + ++decimal_exponent; + } + // at most 9 digits (max_digits10), written from the end + std::array buf; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read + std::size_t start = buf.size(); + do + { + buf[--start] = static_cast('0' + (digits % 10)); + digits /= 10; + } + while (digits != 0); + const auto len = static_cast(buf.size() - start); + + JSON_ASSERT(last - first >= std::numeric_limits::max_digits10 + 6); + JSON_ASSERT(last - first >= 2 + 3 + std::numeric_limits::max_digits10); + static_cast(last); // (only used in the assertions) + std::memcpy(first, buf.data() + start, static_cast(len)); + // as write_positive_grisu2() + return format_buffer(first, len, decimal_exponent, -4, std::numeric_limits::digits10); +} + +/// a positive finite float of a format without Zmij: Grisu2 +template +JSON_HEDLEY_NON_NULL(1, 2) +JSON_HEDLEY_RETURNS_NON_NULL +char* write_positive(char* first, const char* last, FloatType value, std::integral_constant /*grisu2*/) +{ + return write_positive_grisu2(first, last, value); +} + /// a positive finite binary64 number: Zmij (as a long double has the format of /// a double here, its bits are those of the double of the same value) template JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_RETURNS_NON_NULL -char* write_positive(char* first, const char* last, FloatType value, std::true_type /*is_binary64*/) +char* write_positive(char* first, const char* last, FloatType value, std::integral_constant /*binary64*/) { return write_positive_zmij(first, last, value); } -/// a positive finite float of any other format: Grisu2 +/// a positive finite binary32 number: Zmij template JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_RETURNS_NON_NULL -char* write_positive(char* first, const char* last, FloatType value, std::false_type /*is_binary64*/) +char* write_positive(char* first, const char* last, FloatType value, std::integral_constant /*binary32*/) { - return write_positive_grisu2(first, last, value); + return write_positive_zmij_binary32(first, last, value); } -/// a positive finite float: Zmij for binary64 numbers, Grisu2 otherwise +/// a positive finite float: Zmij for binary64 and binary32 numbers, Grisu2 otherwise template JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_RETURNS_NON_NULL char* write_positive(char* first, const char* last, FloatType value) { - return write_positive(first, last, value, is_binary64 {}); + return write_positive(first, last, value, float_conversion {}); } } // namespace dtoa_impl diff --git a/include/nlohmann/detail/conversions/zmij.hpp b/include/nlohmann/detail/conversions/zmij.hpp index 3b2e8e7a3..c851772b4 100644 --- a/include/nlohmann/detail/conversions/zmij.hpp +++ b/include/nlohmann/detail/conversions/zmij.hpp @@ -160,22 +160,37 @@ struct shortest_decimal bool has_digit; ///< whether the shortest decimal is integral * 10 + digit }; -/// The shortest decimal in the rounding interval of a positive finite double -/// given by its bits, the closest one if there are several (to_decimal of -/// Zmij, which keeps the last digit apart: the 15 or 16 digits before it can be -/// converted without a multiplication by 10 first). Always inlined: GCC -/// otherwise calls it, and its result goes through memory. -JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept +/// the bit layout of an IEEE 754 binary format: SigBits significand bits +/// (without the implicit bit) below ExpBits exponent bits +template +struct binary_format +{ + static constexpr unsigned sig_bits = SigBits; + static constexpr unsigned exp_mask = (1u << static_cast(ExpBits)) - 1u; + static constexpr int exp_offset = (1 << (ExpBits - 1)) - 1 + SigBits; // the bias plus the significand bits +}; +using binary64_format = binary_format<52, 11>; +using binary32_format = binary_format<23, 8>; + +/// The shortest decimal in the rounding interval of a positive finite number of +/// the format Format given by its bits, the closest one if there are several +/// (to_decimal of Zmij, which keeps the last digit apart: the 15 or 16 digits +/// of a normal double before it, 6 or 7 of a float, can be converted without a +/// multiplication by 10 first). As in Zmij, the same computation serves both +/// formats; only the bit layout differs. Always inlined: GCC otherwise calls +/// it, and its result goes through memory. +template +JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest_of(std::uint64_t bits) noexcept { constexpr int extra_shift = 9; - const auto raw_exp = static_cast((bits >> 52u) & 0x7FFu); - std::uint64_t bin_sig = bits & ((std::uint64_t{1} << 52u) - 1); + const auto raw_exp = static_cast((bits >> Format::sig_bits) & Format::exp_mask); + std::uint64_t bin_sig = bits & ((std::uint64_t{1} << Format::sig_bits) - 1); // a power of two has a narrower interval below (except the smallest normal) const bool regular = bin_sig != 0 || raw_exp <= 1; - const int bin_exp = (raw_exp == 0 ? 1 : raw_exp) - 1075; + const int bin_exp = (raw_exp == 0 ? 1 : raw_exp) - Format::exp_offset; if (raw_exp != 0) { - bin_sig |= std::uint64_t{1} << 52u; + bin_sig |= std::uint64_t{1} << Format::sig_bits; } // floor(log10(2^bin_exp)), or floor(log10(3/4 * 2^bin_exp)) for the irregular case const int dec_exp = ((bin_exp * 315653) - (regular ? 0 : 131072)) >> 20; @@ -217,6 +232,12 @@ JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexc return shortest_decimal{integral, dec_exp, static_cast(digit), !round_up && !round_down}; } +/// to_shortest_of() for a double given by its bits +JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept +{ + return to_shortest_of(bits); +} + } // namespace zmij } // namespace detail NLOHMANN_JSON_NAMESPACE_END diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index 44a5b6cd1..ebb96c6a6 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -36041,22 +36041,37 @@ struct shortest_decimal bool has_digit; ///< whether the shortest decimal is integral * 10 + digit }; -/// The shortest decimal in the rounding interval of a positive finite double -/// given by its bits, the closest one if there are several (to_decimal of -/// Zmij, which keeps the last digit apart: the 15 or 16 digits before it can be -/// converted without a multiplication by 10 first). Always inlined: GCC -/// otherwise calls it, and its result goes through memory. -JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept +/// the bit layout of an IEEE 754 binary format: SigBits significand bits +/// (without the implicit bit) below ExpBits exponent bits +template +struct binary_format +{ + static constexpr unsigned sig_bits = SigBits; + static constexpr unsigned exp_mask = (1u << static_cast(ExpBits)) - 1u; + static constexpr int exp_offset = (1 << (ExpBits - 1)) - 1 + SigBits; // the bias plus the significand bits +}; +using binary64_format = binary_format<52, 11>; +using binary32_format = binary_format<23, 8>; + +/// The shortest decimal in the rounding interval of a positive finite number of +/// the format Format given by its bits, the closest one if there are several +/// (to_decimal of Zmij, which keeps the last digit apart: the 15 or 16 digits +/// of a normal double before it, 6 or 7 of a float, can be converted without a +/// multiplication by 10 first). As in Zmij, the same computation serves both +/// formats; only the bit layout differs. Always inlined: GCC otherwise calls +/// it, and its result goes through memory. +template +JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest_of(std::uint64_t bits) noexcept { constexpr int extra_shift = 9; - const auto raw_exp = static_cast((bits >> 52u) & 0x7FFu); - std::uint64_t bin_sig = bits & ((std::uint64_t{1} << 52u) - 1); + const auto raw_exp = static_cast((bits >> Format::sig_bits) & Format::exp_mask); + std::uint64_t bin_sig = bits & ((std::uint64_t{1} << Format::sig_bits) - 1); // a power of two has a narrower interval below (except the smallest normal) const bool regular = bin_sig != 0 || raw_exp <= 1; - const int bin_exp = (raw_exp == 0 ? 1 : raw_exp) - 1075; + const int bin_exp = (raw_exp == 0 ? 1 : raw_exp) - Format::exp_offset; if (raw_exp != 0) { - bin_sig |= std::uint64_t{1} << 52u; + bin_sig |= std::uint64_t{1} << Format::sig_bits; } // floor(log10(2^bin_exp)), or floor(log10(3/4 * 2^bin_exp)) for the irregular case const int dec_exp = ((bin_exp * 315653) - (regular ? 0 : 131072)) >> 20; @@ -36098,6 +36113,12 @@ JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexc return shortest_decimal{integral, dec_exp, static_cast(digit), !round_up && !round_down}; } +/// to_shortest_of() for a double given by its bits +JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept +{ + return to_shortest_of(bits); +} + } // namespace zmij } // namespace detail NLOHMANN_JSON_NAMESPACE_END @@ -36111,8 +36132,8 @@ namespace detail /*! @brief implements binary to decimal floating-point conversion: the shortest -digits of Zmij (see zmij.hpp) for IEEE 754 binary64 numbers, and the Grisu2 -algorithm for all other formats. +digits of Zmij (see zmij.hpp) for IEEE 754 binary64 and binary32 numbers, and +the Grisu2 algorithm for all other formats. The Grisu2 implementation is a slightly modified version of the reference implementation which may be obtained from @@ -37459,8 +37480,9 @@ inline char* write_short_decimal(char* first, std::uint64_t digits, int exp) noe @brief whether FloatType is an IEEE 754 binary64 type (a double, or a long double that has the same format, as with MSVC and on Apple's Arm CPUs) -These are the types the conversion of Zmij (see zmij.hpp) is used for; all -others (binary32, or a format the library does not know) use Grisu2. +These are the types the conversion of Zmij (see zmij.hpp) is used for with +write_shortest(); binary32 numbers use it with format_buffer(), and all +others (e.g. the 80-bit long double of x87) use Grisu2. */ template constexpr bool has_binary64_format() noexcept @@ -37474,7 +37496,23 @@ constexpr bool has_binary64_format() noexcept template struct is_binary64 : std::integral_constant()> {}; -/// a positive finite float (other than binary64): Grisu2 and format_buffer() +/// whether FloatType is an IEEE 754 binary32 type (a float); these use the +/// conversion of Zmij as well +template +constexpr bool has_binary32_format() noexcept +{ + return std::numeric_limits::is_iec559 + && std::numeric_limits::digits == 24 + && std::numeric_limits::max_exponent == 128 + && sizeof(FloatType) == sizeof(std::uint32_t); +} + +/// the conversion for a floating-point type: 0 for Grisu2, 1 for Zmij on +/// binary64, 2 for Zmij on binary32 +template +struct float_conversion : std::integral_constant < int, (has_binary64_format() ? 1 : 0) + (has_binary32_format() ? 2 : 0) > {}; + +/// a positive finite float (other than binary64 and binary32): Grisu2 and format_buffer() template JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_RETURNS_NON_NULL @@ -37528,32 +37566,79 @@ char* write_positive_zmij(char* first, const char* last, FloatType value) return first + len; } +/// a positive finite binary32 number: the shortest digits (Zmij), laid out by +/// format_buffer() as the digits of Grisu2 were (only the digits differ: Grisu2 +/// leaves out a decimal on the boundary of the rounding interval and may take +/// the other one of two equally close decimals) +template +JSON_HEDLEY_NON_NULL(1, 2) +JSON_HEDLEY_RETURNS_NON_NULL +char* write_positive_zmij_binary32(char* first, const char* last, FloatType value) +{ + static_assert(has_binary32_format(), + "internal error: this conversion of Zmij needs IEEE 754 binary32 numbers"); + const zmij::shortest_decimal d = zmij::to_shortest_of(bit_cast(value)); + std::uint64_t digits = d.has_digit ? (d.integral * 10) + d.digit : d.integral; + int decimal_exponent = d.has_digit ? d.exponent : d.exponent + 1; + while (digits % 10 == 0) + { + digits /= 10; + ++decimal_exponent; + } + // at most 9 digits (max_digits10), written from the end + std::array buf; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read + std::size_t start = buf.size(); + do + { + buf[--start] = static_cast('0' + (digits % 10)); + digits /= 10; + } + while (digits != 0); + const auto len = static_cast(buf.size() - start); + + JSON_ASSERT(last - first >= std::numeric_limits::max_digits10 + 6); + JSON_ASSERT(last - first >= 2 + 3 + std::numeric_limits::max_digits10); + static_cast(last); // (only used in the assertions) + std::memcpy(first, buf.data() + start, static_cast(len)); + // as write_positive_grisu2() + return format_buffer(first, len, decimal_exponent, -4, std::numeric_limits::digits10); +} + +/// a positive finite float of a format without Zmij: Grisu2 +template +JSON_HEDLEY_NON_NULL(1, 2) +JSON_HEDLEY_RETURNS_NON_NULL +char* write_positive(char* first, const char* last, FloatType value, std::integral_constant /*grisu2*/) +{ + return write_positive_grisu2(first, last, value); +} + /// a positive finite binary64 number: Zmij (as a long double has the format of /// a double here, its bits are those of the double of the same value) template JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_RETURNS_NON_NULL -char* write_positive(char* first, const char* last, FloatType value, std::true_type /*is_binary64*/) +char* write_positive(char* first, const char* last, FloatType value, std::integral_constant /*binary64*/) { return write_positive_zmij(first, last, value); } -/// a positive finite float of any other format: Grisu2 +/// a positive finite binary32 number: Zmij template JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_RETURNS_NON_NULL -char* write_positive(char* first, const char* last, FloatType value, std::false_type /*is_binary64*/) +char* write_positive(char* first, const char* last, FloatType value, std::integral_constant /*binary32*/) { - return write_positive_grisu2(first, last, value); + return write_positive_zmij_binary32(first, last, value); } -/// a positive finite float: Zmij for binary64 numbers, Grisu2 otherwise +/// a positive finite float: Zmij for binary64 and binary32 numbers, Grisu2 otherwise template JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_RETURNS_NON_NULL char* write_positive(char* first, const char* last, FloatType value) { - return write_positive(first, last, value, is_binary64 {}); + return write_positive(first, last, value, float_conversion {}); } } // namespace dtoa_impl diff --git a/tests/src/unit-to_chars.cpp b/tests/src/unit-to_chars.cpp index 3a5a8841d..5bec267dd 100644 --- a/tests/src/unit-to_chars.cpp +++ b/tests/src/unit-to_chars.cpp @@ -22,6 +22,7 @@ using nlohmann::detail::bit_cast; #include #include #include +#include #include #include #include @@ -711,8 +712,122 @@ void check_shortest(double v) CHECK(digits_and_exponent(std::string(std_text.data(), r.ptr)) == de); #endif } +/// a basic_json whose floating-point numbers are floats +using json_with_float = nlohmann::basic_json; + +/// the correctly rounded float of a decimal text (as parse_double()) +float parse_float(const std::string& text) +{ + const json_with_float j = json_with_float::parse(text, nullptr, false); + return j.is_discarded() ? std::numeric_limits::infinity() : j.get(); +} + +/// Check the representation of a positive finite float as check_shortest(): +/// it reads back as the same value, and no representation with fewer digits +/// does. +void check_shortest_float(float v) +{ + std::array buf{}; + char* end = nlohmann::detail::to_chars(buf.data(), buf.data() + 32, v); + const std::string text(buf.data(), end); + CAPTURE(text) + CHECK(bit_cast(parse_float(text)) == bit_cast(v)); + const auto de = digits_and_exponent(text); + const std::string& digits = de.first; + if (digits.size() > 1) + { + const std::uint64_t mid = std::stoull(digits.substr(0, digits.size() - 1)); + for (const std::uint64_t candidate : + { + mid - 1, mid, mid + 1 + }) + { + CAPTURE(candidate) + const std::string shorter = std::to_string(candidate) + "e" + std::to_string(de.second + 1); + CHECK(bit_cast(parse_float(shorter)) != bit_cast(v)); + } + } +#if defined(JSON_HAS_CPP_17) && defined(__cpp_lib_to_chars) && !defined(__INTEL_COMPILER) + std::array std_text {}; + const auto r = std::to_chars(std_text.data(), std_text.data() + std_text.size(), v, std::chars_format::scientific); + CHECK(digits_and_exponent(std::string(std_text.data(), r.ptr)) == de); +#endif +} } // namespace +TEST_CASE("shortest digits of floats") +{ + // (all 2^31 - 2^23 - 1 positive finite floats were checked against + // std::to_chars when this was written; these are the edge cases) + SECTION("boundary values") + { + for (const float v : + { + std::numeric_limits::min(), std::numeric_limits::max(), std::numeric_limits::denorm_min(), + std::nextafter(std::numeric_limits::min(), 0.0f), std::nextafter(std::numeric_limits::max(), 0.0f), + 1.0f, 2.0f, 0.1f, 0.3f, 1e7f, 1e-5f, 123456.7f, 16777216.0f, 16777217.0f, 7.0385307e-26f + }) + { + check_shortest_float(v); + } + // all powers of two (their rounding interval is narrower below) + for (int e = -149; e <= 127; ++e) + { + check_shortest_float(std::ldexp(1.0f, e)); + } + // powers of ten and their neighbors (from 1e-44: 1e-45 reads as the + // smallest float, which is in the list above, and the float below it is 0) + for (int e = -44; e <= 38; ++e) + { + const float p = parse_float("1e" + std::to_string(e)); + check_shortest_float(p); + check_shortest_float(std::nextafter(p, 0.0f)); + check_shortest_float(std::nextafter(p, std::numeric_limits::infinity())); + } + } + + SECTION("where Grisu2 wrote other digits") + { + // Grisu2 leaves out the decimals on the boundary of the rounding + // interval and may take the other one of two equally close decimals; + // both read back as the same float either way + const auto text = [](float v) -> std::string + { + std::array buf{}; + char* end = nlohmann::detail::to_chars(buf.data(), buf.data() + 32, v); + return {buf.data(), end}; + }; + const auto grisu2_text = [](float v) -> std::string + { + std::array buf{}; + char* end = nlohmann::detail::dtoa_impl::write_positive_grisu2(buf.data(), buf.data() + 32, v); + return {buf.data(), end}; + }; + // 134218208 = 2^27 + 32: 1.342182e+08 is the upper end of its rounding interval + CHECK(text(134218208.0f) == "1.342182e+08"); + CHECK(grisu2_text(134218208.0f) == "1.3421821e+08"); + check_shortest_float(134218208.0f); + // 2097156.25 = 2^21 + 4.25: 2097156.2 and 2097156.3 are equally close; the even digit + CHECK(text(2097156.25f) == "2.0971562e+06"); + CHECK(grisu2_text(2097156.25f) == "2.0971563e+06"); + check_shortest_float(2097156.25f); + } + + SECTION("random floats") + { + std::mt19937 rng(5295); // NOLINT(cert-msc32-c,cert-msc51-cpp,bugprone-random-generator-seed): reproducible + for (int i = 0; i < 100000; ++i) + { + const std::uint32_t bits = static_cast(rng()) & 0x7FFFFFFFu; + const auto v = bit_cast(bits); + if (std::isfinite(v) && bits != 0) + { + check_shortest_float(v); + } + } + } +} + TEST_CASE("shortest digits of doubles") { SECTION("powers of ten") @@ -791,11 +906,16 @@ TEST_CASE("shortest digits of doubles") TEST_CASE("choice of the conversion") { using nlohmann::detail::dtoa_impl::is_binary64; + using nlohmann::detail::dtoa_impl::float_conversion; SECTION("by the format of the type") { - // Zmij needs binary64 numbers; everything else uses Grisu2 + // Zmij needs binary64 or binary32 numbers; everything else uses Grisu2 static_assert(!is_binary64::value, "float is not binary64"); + static_assert(float_conversion::value == (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 24 ? 2 : 0), + "float is binary32 where it is IEEE 754 with 24 digits"); + static_assert(float_conversion::value == (is_binary64::value ? 1 : 0), "double is binary64 or uses Grisu2"); + static_assert(float_conversion::value == 0, "integers use Grisu2"); static_assert(is_binary64::value == (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 53), "double is binary64 where it is IEEE 754 with 53 digits"); static_assert(!is_binary64::value, "integers are not binary64"); @@ -805,7 +925,7 @@ TEST_CASE("choice of the conversion") CHECK(is_binary64::value); } - SECTION("float: Grisu2, double: Zmij") + SECTION("float and double: Zmij") { // 5.3165205877497296e+16 is one of the doubles for which Grisu2 does not find the shortest digits constexpr double value = 5.3165205877497296e+16; @@ -817,11 +937,12 @@ TEST_CASE("choice of the conversion") end = nlohmann::detail::dtoa_impl::write_positive_grisu2(buf.data(), last, value); CHECK(std::string(buf.data(), end) == "5.3165205877497296e+16"); - constexpr float f = 1.1754944e-38f; + // 134218208.0f is one of the floats for which Grisu2 does not find the shortest digits + constexpr float f = 134218208.0f; end = nlohmann::detail::dtoa_impl::write_positive(buf.data(), last, f); - const std::string dispatched(buf.data(), end); + CHECK(std::string(buf.data(), end) == "1.342182e+08"); end = nlohmann::detail::dtoa_impl::write_positive_grisu2(buf.data(), last, f); - CHECK(dispatched == std::string(buf.data(), end)); + CHECK(std::string(buf.data(), end) == "1.3421821e+08"); } SECTION("long double with the format of a double: Zmij")