Reputation: 2127
I would like to know if I can assume that the value of a float will not change if I just pass it around functions, without any further calculations. I would like to write some tests for that kind of functions using hardcoded values.
Example :
float identity(float f) { return f; }
Can I write the following test :
TEST() {
EXPECT(identity(1.8f) == 1.8f);
}
Upvotes: 3
Views: 152
Reputation: 308548
In general the C++ standard doesn't make guarantees if it's known that the guarantee will lead to sub-optimal code for some processor architecture.
The legacy x86 floating point processing uses 80-bit registers for calculations. The mere act of moving a value from one of those registers into 64 bits of memory causes rounding to occur.
Upvotes: 3
Reputation: 43662
If you're not performing any lossy operation and just passing the floating point data around it should be safe to assume (assuming there are no interferences or optimization bugs) that the values will remain the same. Just make sure you're not comparing floating point values with literal values interpreted as double (EXPECT(indentity(1.8f) == 1.8);
) or vice-versa.
/paranoid_level on
However you should always check your target architecture behavior with floating point numbers, especially with respect to the IEEE 754 standard: on a system which allows IEEE 754 exceptions under specific circumstances (e.g. -ftz
flags often used in GPUs) you might end up having results inconsistent with your expectations (possibly when combining smart compiler optimizations) since results might be handled internally in a different manner. An example is an architecture which applies to any floating point operation a denormals-are-zero (-daz
) policy.
Upvotes: 1
Reputation: 4367
That is perfectly fine and the value 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 could end up having problems, due to implicit conversions from int/double. however if you compare floats with floats, you're perfectly safe.
Upvotes: 0