C ++ Is there a guarantee for the persistence of untouched float values?

I would like to know if I can assume that the float value will not change if I just pass it around the functions without any further computation. I would like to write some tests for such functions using hardcoded values.

Example:

float identity(float f) { return f; }

      

Can I write the following test:

TEST() {
    EXPECT(identity(1.8f) == 1.8f);
}

      

+3


source to share


3 answers


In general, the C ++ standard makes no guarantees if it knows that the guarantee will result in semi-optimal code for some processor architecture.



Legacy x86 floating point processing uses 80-bit registers for computation. The simple act of moving a value from one of these registers into 64 bits of memory causes rounding.

+3


source


If you are not performing any lossy operations and are just passing floating point data around it, you should safely assume (assuming there is no interference or optimization error) that the values ​​will remain the same. Just make sure you are not comparing floating point values ​​to literal values ​​that are interpreted as double ( EXPECT(indentity(1.8f) == 1.8);

) or vice versa.

/paranoid_level on

      



However, you should always check the behavior of your target floating point architecture, especially with respect to the IEEE 754 standard : on a system that allows IEEE 754 Exceptions under certain circumstances (like flags -ftz

that are often used in GPUs), you can get results not meeting your expectations (perhaps when combining smart compiler optimizations), as the results may be handled internally in a different way. An example is the architecture that applies to any floating point operation, the denormals-are-zero ( -daz

) policy .

+1


source


This is great and the meaning will be identical.

As pointed out in the comments, if you were to write:

TEST() {
    EXPECT(indentity(1.8)  == 1.8f);
    EXPECT(indentity(1.8l) == 1.8f);
}

      

you may have problems due to implicit conversions from int / double. however, if you are comparing floats to floats, you are perfectly safe.

reference

0


source







All Articles