Hasty Briefsbeta

双语

Float and integer arithmetic follow two different paradigms

2 days ago
  • Integer arithmetic safety requires proactive checks before an operation because compilers can optimize away post-issue detection; floating-point errors produce NaN or infinity that propagate without crashing.
  • Common failure patterns include checking for zero denominator or using FLT_EPSILON; these are unreliable because overflow can happen with large/small values regardless.
  • The correct approach for floats is to check if the calculation result is finite using isfinite() or is_finite(), which catches NaN and infinity from any source without rejecting valid inputs.
  • Finite result does not guarantee numerical accuracy; instability can still produce incorrect finite values (e.g., catastrophic cancellation).
  • Special case: in graphics programming (GLSL), NaN propagation is unreliable and isfinite may not work; alternative implementations exist but are limited.
  • Misuse of float checks stems from developer habits shaped by integer safety concerns, float mysticism, and a desire for consistency.