How to actually avoid floating point errors when you need to use float?

前端 未结 4 945
攒了一身酷
攒了一身酷 2021-01-13 18:11

I am trying to affect the translation of a 3D model using some UI buttons to shift the position by 0.1 or -0.1.

My model position is a three dimensional float so sim

4条回答
  •  無奈伤痛
    2021-01-13 18:49

    A simple solution is to either use fixed precision. i.e. an integer 10x or 100x what you want.

    float f = 10;
    f += 0.1f;
    

    becomes

    int i = 100;
    i += 1;  // use an many times as you like
    // use i / 10.0 as required.
    

    I wouldn't use float in any case as you get more rounding errors than double for next to no benefit (unless you have millions of float values) double gives you 8 more digits of precision and with sensible rounding would won't see those errors.

提交回复
热议问题