简体   繁体   中英

Floating-point literal to IEEE-754 binary pattern consistency across compilers

Here's a question with answers on "Cross Platform Floating Point Consistency" but it talks exclusively about runtime consistency (of IEEE floating point).

I'm interested in compile-time consistency, specifically:

If I have a specific floating-point number and want to put a floating-point literal in my source code and have every compiler targeting an IEEE-754 architecture compile that to the same bit pattern that is in fact that float (or double): what do I need to do?

  • A certain number of digits?
  • The exact decimal number for that bit pattern (rather than any decimal number that maps to that binary pattern)?
  • Or?

(I know there has been controversy for years over what you need to do to round-trip floating point values from IEEE format to decimal representations and back and I don't know if this is or is not an issue with floating point literals and the compilers (and the C++ standard).)

You can take advantage of the fact that, while every decimal floating point number does not have an exact representation in the IEEE-754 floating point representation (which uses binary), every IEEE floating point number has an exact representation as a decimal floating point number .

The C++ language specification, in the [lex.fcon] ("floating literals"), discusses floating point literals. After a description of all the parts of a floating point literal, it says

If the scaled value is in the range of representable values for its type, the result is the scaled value if representable, else the larger or smaller representable value nearest the scaled value, chosen in an implementation-defined manner.

(This working is the same in both N3242, a C++11 late working paper, and N4741 from 2018. I was unable to find this description on CPPReference .)

This means that numbers like 0.1 can be either slightly less or slightly more than the desired value, others like 0.5 or 0.000000000931322574615478515625 (2 -30 ) will have that value with all conforming compilers.

You'll need to take your decimal number, get an IEEE-754 representation for the number either just before or just after it, then convert that representation to an equivalent decimal number. Once you have that, all standards conformant compilers that support the IEEE-754 floating point format should give you the exact same constant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM