C++ float or double mathematic mismatch in develop and shipping

float foo = 12000.0f;
float bar = 0.7f;
float result = foo * bar; // 8400.000977
// if i’ll do it with double result will be 8400.000572
this discrepancy appears only in develop and shipping builds, in debug build everything is okay

on android everything is also ok (regardless of build type)


P.S. what I tried:

  • #pragma optimize("", off)
  • PRAGMA_DISABLE_OPTIMIZATION

Thats 100% normal behavior, float point is not accurate type and have specific precision. It comes from fact that byte in memory can only hold integer numbers while fractions are Irrational number and can be infinite size of fraction, thats why computers encode fraction in to integer bytes, but same as any form of encoding it losing data. Thats why when you do float calculations you might get those wierd fractions. The float varable size is fixed (32-bit for single precision float), the bigger integer number in float, the less accurate fraction becomes, because integer will take more bits and there less bits for fraction left. You can read about it here more:

For that exact reason UE4 provide IsNearlyZero and IsNearlyEqual function for such cases

The behavior may differ by CPU (because CPU is the one that does the math calculations) and compilation options, that might be way you have diffrence in build type. But even so you need top be prepared that you might have trash fractions at the end regardless what you gonna use.

Double is double precision float, it takes 64-bit and should be more accurate, but it will still be viable to this either way. Also note that directly setting float varbales will give you better result, because float point calculations are one introducing those inaccuracies, because CPU don’t know that you aim for natural or integer number result, it rether add that fraction then leave it.