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 <mail@nlohmann.me>
This commit is contained in:
7 files changed
+344
-55
No files matched your search
@@ -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.
|
- 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
|
- 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`.
|
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
|
Doubles and floats are converted with the algorithm of [Żmij](https://github.com/vitaut/zmij).
|
||||||
can write more digits than necessary.
|
|
||||||
|
|
||||||
!!! hint "Notes regarding precision of floating-point numbers"
|
!!! hint "Notes regarding precision of floating-point numbers"
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
specifiers, for which the library likewise provides only `#!cpp double` and `#!cpp long double` overloads
|
||||||
(`#!cpp float` is promoted to `#!cpp double`).
|
(`#!cpp float` is promoted to `#!cpp double`).
|
||||||
|
|
||||||
If `#!cpp std::numeric_limits<NumberFloatType>` describes an IEEE 754 binary64 number, `dump` uses the algorithm of
|
If `#!cpp std::numeric_limits<NumberFloatType>` describes an IEEE 754 binary64 or binary32 number, `dump` uses the
|
||||||
Żmij, which produces the shortest representation that round-trips. For IEEE 754 binary32 numbers, it uses Grisu2,
|
algorithm of Żmij, which produces the shortest representation that round-trips. Otherwise the `snprintf` fallback with
|
||||||
which produces a short representation that round-trips. Otherwise the `snprintf` fallback with `max_digits10` digits is
|
`max_digits10` digits is used.
|
||||||
used.
|
|
||||||
|
|
||||||
### Required for the binary formats
|
### Required for the binary formats
|
||||||
|
|
||||||
@@ -591,7 +590,7 @@ binary32 or binary64 field and have no encoding for `#!cpp long double`.
|
|||||||
| Type | Support |
|
| Type | Support |
|
||||||
|--------------------------|-----------------------------------------------------------------------------------------------------------------------|
|
|--------------------------|-----------------------------------------------------------------------------------------------------------------------|
|
||||||
| `#!cpp double` (default) | full; shortest round-trip output through Żmij |
|
| `#!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 |
|
| `#!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 |
|
| any other type | not usable |
|
||||||
|
|
||||||
|
|||||||
@@ -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 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/).
|
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/).
|
||||||
|
|
||||||
|
|||||||
@@ -49,8 +49,8 @@ namespace detail
|
|||||||
|
|
||||||
/*!
|
/*!
|
||||||
@brief implements binary to decimal floating-point conversion: the shortest
|
@brief implements binary to decimal floating-point conversion: the shortest
|
||||||
digits of Zmij (see zmij.hpp) for IEEE 754 binary64 numbers, and the Grisu2
|
digits of Zmij (see zmij.hpp) for IEEE 754 binary64 and binary32 numbers, and
|
||||||
algorithm for all other formats.
|
the Grisu2 algorithm for all other formats.
|
||||||
|
|
||||||
The Grisu2 implementation is a slightly modified version of the reference
|
The Grisu2 implementation is a slightly modified version of the reference
|
||||||
implementation which may be obtained from
|
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
|
@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)
|
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
|
These are the types the conversion of Zmij (see zmij.hpp) is used for with
|
||||||
others (binary32, or a format the library does not know) use Grisu2.
|
write_shortest(); binary32 numbers use it with format_buffer(), and all
|
||||||
|
others (e.g. the 80-bit long double of x87) use Grisu2.
|
||||||
*/
|
*/
|
||||||
template<typename FloatType>
|
template<typename FloatType>
|
||||||
constexpr bool has_binary64_format() noexcept
|
constexpr bool has_binary64_format() noexcept
|
||||||
@@ -1412,7 +1413,23 @@ constexpr bool has_binary64_format() noexcept
|
|||||||
template<typename FloatType>
|
template<typename FloatType>
|
||||||
struct is_binary64 : std::integral_constant<bool, has_binary64_format<FloatType>()> {};
|
struct is_binary64 : std::integral_constant<bool, has_binary64_format<FloatType>()> {};
|
||||||
|
|
||||||
/// 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<typename FloatType>
|
||||||
|
constexpr bool has_binary32_format() noexcept
|
||||||
|
{
|
||||||
|
return std::numeric_limits<FloatType>::is_iec559
|
||||||
|
&& std::numeric_limits<FloatType>::digits == 24
|
||||||
|
&& std::numeric_limits<FloatType>::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<typename FloatType>
|
||||||
|
struct float_conversion : std::integral_constant < int, (has_binary64_format<FloatType>() ? 1 : 0) + (has_binary32_format<FloatType>() ? 2 : 0) > {};
|
||||||
|
|
||||||
|
/// a positive finite float (other than binary64 and binary32): Grisu2 and format_buffer()
|
||||||
template<typename FloatType>
|
template<typename FloatType>
|
||||||
JSON_HEDLEY_NON_NULL(1, 2)
|
JSON_HEDLEY_NON_NULL(1, 2)
|
||||||
JSON_HEDLEY_RETURNS_NON_NULL
|
JSON_HEDLEY_RETURNS_NON_NULL
|
||||||
@@ -1466,32 +1483,79 @@ char* write_positive_zmij(char* first, const char* last, FloatType value)
|
|||||||
return first + len;
|
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<typename FloatType>
|
||||||
|
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<FloatType>(),
|
||||||
|
"internal error: this conversion of Zmij needs IEEE 754 binary32 numbers");
|
||||||
|
const zmij::shortest_decimal d = zmij::to_shortest_of<zmij::binary32_format>(bit_cast<std::uint32_t>(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<char, 9> buf; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read
|
||||||
|
std::size_t start = buf.size();
|
||||||
|
do
|
||||||
|
{
|
||||||
|
buf[--start] = static_cast<char>('0' + (digits % 10));
|
||||||
|
digits /= 10;
|
||||||
|
}
|
||||||
|
while (digits != 0);
|
||||||
|
const auto len = static_cast<int>(buf.size() - start);
|
||||||
|
|
||||||
|
JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
|
||||||
|
JSON_ASSERT(last - first >= 2 + 3 + std::numeric_limits<FloatType>::max_digits10);
|
||||||
|
static_cast<void>(last); // (only used in the assertions)
|
||||||
|
std::memcpy(first, buf.data() + start, static_cast<std::size_t>(len));
|
||||||
|
// as write_positive_grisu2()
|
||||||
|
return format_buffer(first, len, decimal_exponent, -4, std::numeric_limits<FloatType>::digits10);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// a positive finite float of a format without Zmij: Grisu2
|
||||||
|
template<typename FloatType>
|
||||||
|
JSON_HEDLEY_NON_NULL(1, 2)
|
||||||
|
JSON_HEDLEY_RETURNS_NON_NULL
|
||||||
|
char* write_positive(char* first, const char* last, FloatType value, std::integral_constant<int, 0> /*grisu2*/)
|
||||||
|
{
|
||||||
|
return write_positive_grisu2(first, last, value);
|
||||||
|
}
|
||||||
|
|
||||||
/// a positive finite binary64 number: Zmij (as a long double has the format of
|
/// 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)
|
/// a double here, its bits are those of the double of the same value)
|
||||||
template<typename FloatType>
|
template<typename FloatType>
|
||||||
JSON_HEDLEY_NON_NULL(1, 2)
|
JSON_HEDLEY_NON_NULL(1, 2)
|
||||||
JSON_HEDLEY_RETURNS_NON_NULL
|
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<int, 1> /*binary64*/)
|
||||||
{
|
{
|
||||||
return write_positive_zmij(first, last, value);
|
return write_positive_zmij(first, last, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// a positive finite float of any other format: Grisu2
|
/// a positive finite binary32 number: Zmij
|
||||||
template<typename FloatType>
|
template<typename FloatType>
|
||||||
JSON_HEDLEY_NON_NULL(1, 2)
|
JSON_HEDLEY_NON_NULL(1, 2)
|
||||||
JSON_HEDLEY_RETURNS_NON_NULL
|
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<int, 2> /*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<typename FloatType>
|
template<typename FloatType>
|
||||||
JSON_HEDLEY_NON_NULL(1, 2)
|
JSON_HEDLEY_NON_NULL(1, 2)
|
||||||
JSON_HEDLEY_RETURNS_NON_NULL
|
JSON_HEDLEY_RETURNS_NON_NULL
|
||||||
char* write_positive(char* first, const char* last, FloatType value)
|
char* write_positive(char* first, const char* last, FloatType value)
|
||||||
{
|
{
|
||||||
return write_positive(first, last, value, is_binary64<FloatType> {});
|
return write_positive(first, last, value, float_conversion<FloatType> {});
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace dtoa_impl
|
} // namespace dtoa_impl
|
||||||
|
|||||||
@@ -160,22 +160,37 @@ struct shortest_decimal
|
|||||||
bool has_digit; ///< whether the shortest decimal is integral * 10 + digit
|
bool has_digit; ///< whether the shortest decimal is integral * 10 + digit
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The shortest decimal in the rounding interval of a positive finite double
|
/// the bit layout of an IEEE 754 binary format: SigBits significand bits
|
||||||
/// given by its bits, the closest one if there are several (to_decimal of
|
/// (without the implicit bit) below ExpBits exponent bits
|
||||||
/// Zmij, which keeps the last digit apart: the 15 or 16 digits before it can be
|
template<int SigBits, int ExpBits>
|
||||||
/// converted without a multiplication by 10 first). Always inlined: GCC
|
struct binary_format
|
||||||
/// otherwise calls it, and its result goes through memory.
|
{
|
||||||
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept
|
static constexpr unsigned sig_bits = SigBits;
|
||||||
|
static constexpr unsigned exp_mask = (1u << static_cast<unsigned>(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<typename Format>
|
||||||
|
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest_of(std::uint64_t bits) noexcept
|
||||||
{
|
{
|
||||||
constexpr int extra_shift = 9;
|
constexpr int extra_shift = 9;
|
||||||
const auto raw_exp = static_cast<int>((bits >> 52u) & 0x7FFu);
|
const auto raw_exp = static_cast<int>((bits >> Format::sig_bits) & Format::exp_mask);
|
||||||
std::uint64_t bin_sig = bits & ((std::uint64_t{1} << 52u) - 1);
|
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)
|
// a power of two has a narrower interval below (except the smallest normal)
|
||||||
const bool regular = bin_sig != 0 || raw_exp <= 1;
|
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)
|
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
|
// 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;
|
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<unsigned char>(digit), !round_up && !round_down};
|
return shortest_decimal{integral, dec_exp, static_cast<unsigned char>(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<binary64_format>(bits);
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace zmij
|
} // namespace zmij
|
||||||
} // namespace detail
|
} // namespace detail
|
||||||
NLOHMANN_JSON_NAMESPACE_END
|
NLOHMANN_JSON_NAMESPACE_END
|
||||||
Generated
+106
-21
@@ -36041,22 +36041,37 @@ struct shortest_decimal
|
|||||||
bool has_digit; ///< whether the shortest decimal is integral * 10 + digit
|
bool has_digit; ///< whether the shortest decimal is integral * 10 + digit
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The shortest decimal in the rounding interval of a positive finite double
|
/// the bit layout of an IEEE 754 binary format: SigBits significand bits
|
||||||
/// given by its bits, the closest one if there are several (to_decimal of
|
/// (without the implicit bit) below ExpBits exponent bits
|
||||||
/// Zmij, which keeps the last digit apart: the 15 or 16 digits before it can be
|
template<int SigBits, int ExpBits>
|
||||||
/// converted without a multiplication by 10 first). Always inlined: GCC
|
struct binary_format
|
||||||
/// otherwise calls it, and its result goes through memory.
|
{
|
||||||
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept
|
static constexpr unsigned sig_bits = SigBits;
|
||||||
|
static constexpr unsigned exp_mask = (1u << static_cast<unsigned>(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<typename Format>
|
||||||
|
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest_of(std::uint64_t bits) noexcept
|
||||||
{
|
{
|
||||||
constexpr int extra_shift = 9;
|
constexpr int extra_shift = 9;
|
||||||
const auto raw_exp = static_cast<int>((bits >> 52u) & 0x7FFu);
|
const auto raw_exp = static_cast<int>((bits >> Format::sig_bits) & Format::exp_mask);
|
||||||
std::uint64_t bin_sig = bits & ((std::uint64_t{1} << 52u) - 1);
|
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)
|
// a power of two has a narrower interval below (except the smallest normal)
|
||||||
const bool regular = bin_sig != 0 || raw_exp <= 1;
|
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)
|
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
|
// 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;
|
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<unsigned char>(digit), !round_up && !round_down};
|
return shortest_decimal{integral, dec_exp, static_cast<unsigned char>(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<binary64_format>(bits);
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace zmij
|
} // namespace zmij
|
||||||
} // namespace detail
|
} // namespace detail
|
||||||
NLOHMANN_JSON_NAMESPACE_END
|
NLOHMANN_JSON_NAMESPACE_END
|
||||||
@@ -36111,8 +36132,8 @@ namespace detail
|
|||||||
|
|
||||||
/*!
|
/*!
|
||||||
@brief implements binary to decimal floating-point conversion: the shortest
|
@brief implements binary to decimal floating-point conversion: the shortest
|
||||||
digits of Zmij (see zmij.hpp) for IEEE 754 binary64 numbers, and the Grisu2
|
digits of Zmij (see zmij.hpp) for IEEE 754 binary64 and binary32 numbers, and
|
||||||
algorithm for all other formats.
|
the Grisu2 algorithm for all other formats.
|
||||||
|
|
||||||
The Grisu2 implementation is a slightly modified version of the reference
|
The Grisu2 implementation is a slightly modified version of the reference
|
||||||
implementation which may be obtained from
|
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
|
@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)
|
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
|
These are the types the conversion of Zmij (see zmij.hpp) is used for with
|
||||||
others (binary32, or a format the library does not know) use Grisu2.
|
write_shortest(); binary32 numbers use it with format_buffer(), and all
|
||||||
|
others (e.g. the 80-bit long double of x87) use Grisu2.
|
||||||
*/
|
*/
|
||||||
template<typename FloatType>
|
template<typename FloatType>
|
||||||
constexpr bool has_binary64_format() noexcept
|
constexpr bool has_binary64_format() noexcept
|
||||||
@@ -37474,7 +37496,23 @@ constexpr bool has_binary64_format() noexcept
|
|||||||
template<typename FloatType>
|
template<typename FloatType>
|
||||||
struct is_binary64 : std::integral_constant<bool, has_binary64_format<FloatType>()> {};
|
struct is_binary64 : std::integral_constant<bool, has_binary64_format<FloatType>()> {};
|
||||||
|
|
||||||
/// 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<typename FloatType>
|
||||||
|
constexpr bool has_binary32_format() noexcept
|
||||||
|
{
|
||||||
|
return std::numeric_limits<FloatType>::is_iec559
|
||||||
|
&& std::numeric_limits<FloatType>::digits == 24
|
||||||
|
&& std::numeric_limits<FloatType>::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<typename FloatType>
|
||||||
|
struct float_conversion : std::integral_constant < int, (has_binary64_format<FloatType>() ? 1 : 0) + (has_binary32_format<FloatType>() ? 2 : 0) > {};
|
||||||
|
|
||||||
|
/// a positive finite float (other than binary64 and binary32): Grisu2 and format_buffer()
|
||||||
template<typename FloatType>
|
template<typename FloatType>
|
||||||
JSON_HEDLEY_NON_NULL(1, 2)
|
JSON_HEDLEY_NON_NULL(1, 2)
|
||||||
JSON_HEDLEY_RETURNS_NON_NULL
|
JSON_HEDLEY_RETURNS_NON_NULL
|
||||||
@@ -37528,32 +37566,79 @@ char* write_positive_zmij(char* first, const char* last, FloatType value)
|
|||||||
return first + len;
|
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<typename FloatType>
|
||||||
|
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<FloatType>(),
|
||||||
|
"internal error: this conversion of Zmij needs IEEE 754 binary32 numbers");
|
||||||
|
const zmij::shortest_decimal d = zmij::to_shortest_of<zmij::binary32_format>(bit_cast<std::uint32_t>(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<char, 9> buf; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read
|
||||||
|
std::size_t start = buf.size();
|
||||||
|
do
|
||||||
|
{
|
||||||
|
buf[--start] = static_cast<char>('0' + (digits % 10));
|
||||||
|
digits /= 10;
|
||||||
|
}
|
||||||
|
while (digits != 0);
|
||||||
|
const auto len = static_cast<int>(buf.size() - start);
|
||||||
|
|
||||||
|
JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
|
||||||
|
JSON_ASSERT(last - first >= 2 + 3 + std::numeric_limits<FloatType>::max_digits10);
|
||||||
|
static_cast<void>(last); // (only used in the assertions)
|
||||||
|
std::memcpy(first, buf.data() + start, static_cast<std::size_t>(len));
|
||||||
|
// as write_positive_grisu2()
|
||||||
|
return format_buffer(first, len, decimal_exponent, -4, std::numeric_limits<FloatType>::digits10);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// a positive finite float of a format without Zmij: Grisu2
|
||||||
|
template<typename FloatType>
|
||||||
|
JSON_HEDLEY_NON_NULL(1, 2)
|
||||||
|
JSON_HEDLEY_RETURNS_NON_NULL
|
||||||
|
char* write_positive(char* first, const char* last, FloatType value, std::integral_constant<int, 0> /*grisu2*/)
|
||||||
|
{
|
||||||
|
return write_positive_grisu2(first, last, value);
|
||||||
|
}
|
||||||
|
|
||||||
/// a positive finite binary64 number: Zmij (as a long double has the format of
|
/// 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)
|
/// a double here, its bits are those of the double of the same value)
|
||||||
template<typename FloatType>
|
template<typename FloatType>
|
||||||
JSON_HEDLEY_NON_NULL(1, 2)
|
JSON_HEDLEY_NON_NULL(1, 2)
|
||||||
JSON_HEDLEY_RETURNS_NON_NULL
|
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<int, 1> /*binary64*/)
|
||||||
{
|
{
|
||||||
return write_positive_zmij(first, last, value);
|
return write_positive_zmij(first, last, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// a positive finite float of any other format: Grisu2
|
/// a positive finite binary32 number: Zmij
|
||||||
template<typename FloatType>
|
template<typename FloatType>
|
||||||
JSON_HEDLEY_NON_NULL(1, 2)
|
JSON_HEDLEY_NON_NULL(1, 2)
|
||||||
JSON_HEDLEY_RETURNS_NON_NULL
|
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<int, 2> /*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<typename FloatType>
|
template<typename FloatType>
|
||||||
JSON_HEDLEY_NON_NULL(1, 2)
|
JSON_HEDLEY_NON_NULL(1, 2)
|
||||||
JSON_HEDLEY_RETURNS_NON_NULL
|
JSON_HEDLEY_RETURNS_NON_NULL
|
||||||
char* write_positive(char* first, const char* last, FloatType value)
|
char* write_positive(char* first, const char* last, FloatType value)
|
||||||
{
|
{
|
||||||
return write_positive(first, last, value, is_binary64<FloatType> {});
|
return write_positive(first, last, value, float_conversion<FloatType> {});
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace dtoa_impl
|
} // namespace dtoa_impl
|
||||||
|
|||||||
+126
-5
@@ -22,6 +22,7 @@ using nlohmann::detail::bit_cast;
|
|||||||
#include <cstdio>
|
#include <cstdio>
|
||||||
#include <cstdlib>
|
#include <cstdlib>
|
||||||
#include <limits>
|
#include <limits>
|
||||||
|
#include <map>
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
@@ -711,8 +712,122 @@ void check_shortest(double v)
|
|||||||
CHECK(digits_and_exponent(std::string(std_text.data(), r.ptr)) == de);
|
CHECK(digits_and_exponent(std::string(std_text.data(), r.ptr)) == de);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
/// a basic_json whose floating-point numbers are floats
|
||||||
|
using json_with_float = nlohmann::basic_json<std::map, std::vector, std::string, bool, std::int64_t, std::uint64_t, float>;
|
||||||
|
|
||||||
|
/// 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<float>::infinity() : j.get<float>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<char, 33> 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<std::uint32_t>(parse_float(text)) == bit_cast<std::uint32_t>(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<std::uint32_t>(parse_float(shorter)) != bit_cast<std::uint32_t>(v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#if defined(JSON_HAS_CPP_17) && defined(__cpp_lib_to_chars) && !defined(__INTEL_COMPILER)
|
||||||
|
std::array<char, 64> 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
|
} // 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<float>::min(), std::numeric_limits<float>::max(), std::numeric_limits<float>::denorm_min(),
|
||||||
|
std::nextafter(std::numeric_limits<float>::min(), 0.0f), std::nextafter(std::numeric_limits<float>::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<float>::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<char, 33> 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<char, 33> 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<std::uint32_t>(rng()) & 0x7FFFFFFFu;
|
||||||
|
const auto v = bit_cast<float>(bits);
|
||||||
|
if (std::isfinite(v) && bits != 0)
|
||||||
|
{
|
||||||
|
check_shortest_float(v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
TEST_CASE("shortest digits of doubles")
|
TEST_CASE("shortest digits of doubles")
|
||||||
{
|
{
|
||||||
SECTION("powers of ten")
|
SECTION("powers of ten")
|
||||||
@@ -791,11 +906,16 @@ TEST_CASE("shortest digits of doubles")
|
|||||||
TEST_CASE("choice of the conversion")
|
TEST_CASE("choice of the conversion")
|
||||||
{
|
{
|
||||||
using nlohmann::detail::dtoa_impl::is_binary64;
|
using nlohmann::detail::dtoa_impl::is_binary64;
|
||||||
|
using nlohmann::detail::dtoa_impl::float_conversion;
|
||||||
|
|
||||||
SECTION("by the format of the type")
|
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<float>::value, "float is not binary64");
|
static_assert(!is_binary64<float>::value, "float is not binary64");
|
||||||
|
static_assert(float_conversion<float>::value == (std::numeric_limits<float>::is_iec559 && std::numeric_limits<float>::digits == 24 ? 2 : 0),
|
||||||
|
"float is binary32 where it is IEEE 754 with 24 digits");
|
||||||
|
static_assert(float_conversion<double>::value == (is_binary64<double>::value ? 1 : 0), "double is binary64 or uses Grisu2");
|
||||||
|
static_assert(float_conversion<int>::value == 0, "integers use Grisu2");
|
||||||
static_assert(is_binary64<double>::value == (std::numeric_limits<double>::is_iec559 && std::numeric_limits<double>::digits == 53),
|
static_assert(is_binary64<double>::value == (std::numeric_limits<double>::is_iec559 && std::numeric_limits<double>::digits == 53),
|
||||||
"double is binary64 where it is IEEE 754 with 53 digits");
|
"double is binary64 where it is IEEE 754 with 53 digits");
|
||||||
static_assert(!is_binary64<int>::value, "integers are not binary64");
|
static_assert(!is_binary64<int>::value, "integers are not binary64");
|
||||||
@@ -805,7 +925,7 @@ TEST_CASE("choice of the conversion")
|
|||||||
CHECK(is_binary64<double>::value);
|
CHECK(is_binary64<double>::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
|
// 5.3165205877497296e+16 is one of the doubles for which Grisu2 does not find the shortest digits
|
||||||
constexpr double value = 5.3165205877497296e+16;
|
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);
|
end = nlohmann::detail::dtoa_impl::write_positive_grisu2(buf.data(), last, value);
|
||||||
CHECK(std::string(buf.data(), end) == "5.3165205877497296e+16");
|
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);
|
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);
|
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")
|
SECTION("long double with the format of a double: Zmij")
|
||||||
|
|||||||
Reference in new issue
Block a user