Can we say that it is always true that 0.5 * x + 0.5 * x == x?

0.5is (negative) power 2, which means that it is accurately represented by the IEEE-754 floating point binary format. This is exactly the column 0'01111110'00000000000000000000000.

Based on my quick tests with optimizations disabled ( -O0), it turns out that if y = 0.5 * x, then y + y == x. But is it always guaranteed by the IEEE-754 standard?

I know that, generally speaking, if n- a positive integral power 2and m = 1.0 / n, y = m * xthen adding ytogether njust does not x. But it seems n = 2so.

Did I miss something?

+4
source share
1 answer

No, here is a trivial example of a counter doublewith floating point precision:

double x = 4.9E-324; // minimum positive value
double y = x * 0.5; // this doesn't only look like a zero this positive zero all 0 bits
bool test = y + y == x; // false

Floating-point numbers in IEEE-754 have limited accuracy, and we may lose information when divided by 2. In most cases, when you decrease the number, you get accuracy, you can reduce the exponent, but, as above, this is not always enough. Sometimes you cannot reduce the exponent.

Anything that has a minimal exponent and an odd mantissa will not contain equality. Such an example x = 5.0E-322.

+6
source

Source: https://habr.com/ru/post/1678927/


All Articles