Why does Swift interpret 8.95 as 8.94999 repeating, please?
What kind of internal calculator is Swift using???
Screen shot for reference :
Why does Swift interpret 8.95 as 8.94999 repeating, please?
What kind of internal calculator is Swift using???
Screen shot for reference :
Floating point numbers, which almost all computer languages use, cannot exactly represent all base 10 decimal numbers. You can use the Decimal
type instead if you need this, but most programs don’t need it.
You can read more about why this is internally here: Floating-point arithmetic - Wikipedia
Yeah, floating-point yadda yadda yadda, but this is still a playground bug.
The Swift standard library formats a Double
using the fewest digits needed to parse back to the same Double
:
If it's built in to Swift then there's no excuse for the playground to use all those extra digits.
Thank you, @mayoff , @tera, @David_Smith for your help.
Technically rounding floating point numbers is built in to String rather then the language as a whole. The playground is giving a result that reflects reality better. I prefer that behavior since it is more obvious you are working with an imprecise floating-point representation. That representation matters when not printing the value. If you need an exact number, that is what Decimal is for. If a 32-bit Float were used instead the playground would correctly show 8.94999980926513671875 due to the even lower precision. It is important to remember that floating point numbers will always be slightly skewed which is why you can’t rely on equality operations working after some math is performed that may grow the error. This is a common mistake made by those first learning programming and can result in subtle bugs.
Here is a good resource that shows why the playground is giving the correct value, while the string is just giving a more human friendly value: IEEE-754 Floating Point Converter
Basically use Decimal for finance and Double/Float for graphics or other cases where approximations are fine.
In fact, it looks like this might be explained in a future lesson for your class. I see “Limits of Floats” in another page of your playground.
To put a fine point on it, one can evaluate the following statement in Swift (or most common programming languages):
8.949999999999999 == 8.95 // true
Another interesting example:
Double(8.95) == Double(Float(8.95)) // false
Or the classic example:
0.1 + 0.2 == 0.3 // false
Ha! .... Apologies for jumping the gun on my workbook!