user3496846 - 9 months ago 36

C++ Question

Given that the numbers are relatively small (~ -1 to ~ 1) and are floats and randomly generated, can you get 'floating point invalid operation' by adding too many of them? I am asking because that's what apparently happens in my program right now and very rarely too. Also, how does one disable (or avoid) this exception?

Just in case, my compiler is gcc (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 5.1.0.

EDIT As requested I am providing the code. However, the addition of floats causing the error is only my conjecture, *that's why I came here*, to find out if that could be my problem. If I run code below, is it reasonable that I can get the error?

`#include <iostream>`

int main()

{

float sum = 0, add = 0;

while (true)

{

add = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);

if (rand() % 2) add *= -1;

sum += add;

}

}

EDIT 2: I don't get the error with the code above, I just need to know if it could happen.

Answer Source

The IEEE 754 standard defines the following situations in which an “invalid operation” floating-point exception occurs:

- operating on a signaling NaN
- multiplying 0×∞ or ∞×0
- adding/subtracting infinities such as ∞−∞, −∞+∞ and so on
- dividing 0/0 or ∞/∞
- calculating the remainder of x/y when y=0 or x=∞ and neither is NaN
- taking the square root of a negative number
- quantize when the result does not fit in the destination format or when one operand is finite and the other is infinite
- converting NaN, ∞ or an out-of-target-range float to an integer
- comparing unordered floating-point values with signaling
- calculating an integer logarithm of NaN, ∞ or 0

Your example code will not trigger any of those cases, so the problem would be elsewhere in your code.