Search code examples
c++rounding-error

Preventing Rounding Errors


I was just reading about rounding errors in C++. So, if I'm making a math intense program (or any important calculations) should I just drop floats all together and use only doubles or is there an easier way to prevent rounding errors?


Solution

  • Obligatory lecture: What Every Programmer Should Know About Floating-Point Arithmetic.

    Also, try reading IEEE Floating Point standard.

    You'll always get rounding errors. Unless you use an infinite arbitrary precision library, like gmplib. You have to decide if your application really needs this kind of effort.

    Or, you could use integer arithmetic, converting to floats only when needed. This is still hard to do, you have to decide if it's worth it.

    Lastly, you can use float or double taking care not to make assumption about values at the limit of representation's precision. I'd wish this Valgrind plugin was implemented (grep for float)...