Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is x/a the same as x*(1/a) for floats?

With float a = ...; and float inva = 1/a; is x / a the same as x * inva?

And what is with this case:

unsigned i = ...;
float v1 = static_cast<float>(i) / 4294967295.0f;
float scl = 1.0f / 4294967295.0f;
float v2 = static_cast<float>(i) * scl;

Is v1 equal to v2 for all unsigned integers?

like image 885
Danvil Avatar asked Mar 26 '14 14:03

Danvil


2 Answers

is v1 equal to v2 for all unsigned integers?

Yes, because 4294967295.0f is a power of two. Division and multiplication by the reciprocal are equivalent when the divisor is a power of two (assuming the computation of the reciprocal does not overflow or underflow to zero).

Division and multiplication by the reciprocal are not equivalent in general, only in the particular case of powers of two. The reason is that for (almost all) powers of two y, the computation of 1 / y is exact, so that x * (1 / y) only rounds once, just like x / y only rounds once.

like image 116
Pascal Cuoq Avatar answered Sep 28 '22 06:09

Pascal Cuoq


No, the result will not always be the same. The way you group the operands in floating point multiplication, or division in this case, has an effect on the numerical accuracy of the answer. Thus, the product a*(1/b) might differ from a/b. Check the wikipedia article http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems.

like image 42
Rontogiannis Aristofanis Avatar answered Sep 28 '22 07:09

Rontogiannis Aristofanis