I was surprised to see the answer to 3.14 + 42.0 be returned as 45.139999 when the computer added those values together as float variables. Reading another topic, it mentioned that you can’t always trust the computer to handle floats the same as integers and the results may be incorrect. I ended up changing the float variables to double and the answered appeared as I had expected it as 45.140000. With memory not as big an issue nowadays, why would I ever want to use float and worry about incorrect results?
They are not incorrect; they just contain tiny errors.
Even with doubles, similar errors are bound to occur.
Sometimes real numbers (values of type float or double) are impossible to represent without errors because only a finite number of bits are used to represent the values.
Therefore, one has to be very careful when comparing float values or double values for exact equality.
Ok, if something has tiny errors, we usually call that incorrect (or alternative facts)
Nonetheless! Here’s a handy guide for why things are the way things are:
My favorite section in there explains why this happens, and why we put up with it (emphasis mine):
“Why do computers use such a stupid system?”
“It’s not stupid, just different. Decimal numbers cannot accurately represent a number like 1/3, so you have to round to something like 0.33 - and you don’t expect 0.33 + 0.33 + 0.33 to add up to 1, either - do you?”