You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Float is a 32-bit representation, and with 32 bits, the two numbers "1.234" and "1.2339999675750732" have identical representations. Either way is "correct" to print a float. There is no imprecision here, just a representation that is "less pretty".
When cout outputs "c" as "1.234", it is actually lying and printing something less precise than it actually is. If you tell cout you want full precision, then you will get identical results to what nlohmann::json is doing. (add "std::cout.precision(17);" to your program).
>>> def float2hex(num):
... return ''.join('%02x' % ord(c) for c in struct.pack('!f', num))
...
>>> def double2hex(num):
... return ''.join('%02x' % ord(c) for c in struct.pack('!d', num))
...
>>> float2hex(1.2339999675750732)
'3f9df3b6'
>>> float2hex(1.234)
'3f9df3b6'
>>>
>>> double2hex(1.234)
'3ff3be76c8b43958'
>>> double2hex(1.2339999675750732)
'3ff3be76c0000000'
Activity
jaredgrubb commentedon Jul 17, 2018
Float is a 32-bit representation, and with 32 bits, the two numbers "1.234" and "1.2339999675750732" have identical representations. Either way is "correct" to print a float. There is no imprecision here, just a representation that is "less pretty".
When cout outputs "c" as "1.234", it is actually lying and printing something less precise than it actually is. If you tell cout you want full precision, then you will get identical results to what nlohmann::json is doing. (add "std::cout.precision(17);" to your program).
jmlemetayer commentedon Jul 17, 2018
Wow very impressive response. Thanks for the explanation.
As I understood the background behind my issue, I close it.
nlohmann commentedon Jul 18, 2018
@jaredgrubb Thanks so much for the detailed response. I am currently overworking the documentation, and this definitely should go in there!