How to reproduce this behavior? https://isocpp.org/wiki/faq/newbie#floating-point-arith2
To be precise, in the following code, parameters x
and y
are equal; they can be equal to 1.0 or any other value.
void foo(double x, double y)
{
double cos_x = cos(x);
double cos_y = cos(y);
// the behavior might depend on what's in here
if (cos_x != cos_y) {
std::cout << "Huh?!?\n"; // You might end up here when x == y!!
}
}
Some compiler options? Loop? Any idea?
I would try doing it the way it is done in the linked example: without storing the results to temporary variables. The article mentions that floating point arithmetic is often calculated in registers that have more bits than the RAM. If there is, for example, only one floating point arithmetic register, then after doing the
cos
calculation, the result has to be stored in RAM in order to do the othercos
calculation. From the article:When you store both results in variables (depending on optimization, etc.) there is a good chance that the result of the second
cos
calculation will also be stored in RAM before the calculation. Since the results will be truncated the same way, they will compare as==
.