Floating-point & integer division

Applies to: general, python, cpp

Floating-point numbers (float, double) approximate real numbers and carry tiny rounding errors, so compare them with a tolerance, not ==. A classic trap: dividing two integers truncates (5 / 2 == 2); cast to a real first to get 2.5.

double half = (double)1 / 2;   // 0.5, not 0
if (std::fabs(x - 0.3) < 1e-9) // compare floats with a tolerance

See also: data-type