Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 582
Freesnöw Avatar asked Aug 07 '26 14:08

Freesnöw


2 Answers

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)...

like image 134
Mihai Maruseac Avatar answered Aug 10 '26 23:08

Mihai Maruseac


The rounding errors are normally very insignificant, even using floats. Mathematically-intense programs like games, which do very large numbers of floating-point computations, often still use single-precision.

like image 41
Puppy Avatar answered Aug 10 '26 23:08

Puppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!