How to reproduce floating point cos(x)!=cos(x)

153 views Asked by At

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?

1

There are 1 answers

0
Daniel On

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 other cos calculation. From the article:

Suppose your code computes cos(x), then truncates that result and stores it into a temporary variable, say tmp. It might then compute cos(y), and (drum roll please) compare the untruncated result of cos(y) with tmp, that is, with the truncated result of cos(x).

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 ==.