r/programminghelp • u/j10b100 • Dec 10 '19
Someone explain why round off error in java happens please, I seriously don’t understand why I can not just do double == double and carry on with my day
3
Upvotes
r/programminghelp • u/j10b100 • Dec 10 '19
4
u/marko312 Dec 10 '19 edited Dec 10 '19
Both
doubleandfloatare floating-point data types, which store the decimal value as a power of some base, the sign and a value for the significant digits.However, the value for holding the significant digits isn't perfect - just like you can't quite write 1/3 with finite digits in a decimal system (0.33333333...), something seemingly as simple as 0.3 can also not fully be represented in binary in this format. You can play around with a visualization of a
floathere.This, in turn, means that the stored values are ever-so-slightly different from the actual values they should represent, eventually leading to rounding errors after multiple operations.
If you need extremely high precision, you can try using integer types, rational number types (essentially a fraction) or (such as if you really need the values of trigonometric functions or square roots), an external library providing high-precision data types.
However, for most purposes, you can use a
doubleand just round off the last couple of digits.