Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

floor(a/(double)b)*b==a if a%b==0 in C?

Wondering if below assertion is correct if a and b are both integers > 0. Can float number precision cause problem in this condition?

assert(a%b || floor(a/(double)b)*b==a);
like image 639
poordeveloper Avatar asked Jan 20 '26 17:01

poordeveloper


1 Answers

If the first part of the condition is false, then a is a multiple of b.

The conversion to double of an integer is generally exact (if double is IEEE 754's binary64, it is exact for integers up to 253). Assuming these conditions, a/(double)b is the double nearest to the real division of a by b. Since the real result is an integer below 253, it is exactly representable, so no rounding occurs (in other words the floating-point division is exact).

floor() applied to a double that represents an integer returns the same integer.

The floating-point multiplication is exact for the same reasons as the division, and produces exactly a.

Conclusion: the condition in the assert is always true, for a and b between -253 and 253, for a platform that implements double as binary64, with or without excess precision.

like image 80
Pascal Cuoq Avatar answered Jan 22 '26 11:01

Pascal Cuoq