Search code examples
c++floating-pointrounding-error

Safely invert floating point calculation


I wonder what is the correct way to invert this calculation:

float x = a * 25.0f + b; // where a and b are integers and b is in [0-25[

How can I avoid possible floating-point rounding errors. The answers are obvious even if x has some error so it should be possible to implement.


Solution

  • Try using modulo arithmetics, i.e. integer division / and remainder %:

    int a = ((int) (x + 0.5f)) / 25; 
    int b = ((int) (x + 0.5f)) % 25; 
    

    if x can have round up errors, e.g. x = 53.999997 instead of 54 then round it to the nearest integer: (int) (x + 0.5f). Please, notice that x should be small enough to be cast to int: x = 1e30f will definitely fail.