x = 19.93
y = 20.00
z = y – x
The output is 0.0700000000028 Why is that so?
Improve the code so that the output is to two decimal places
x = 19.93
It has to do with the way computers work with decimal numbers. Since there are no fractions in binary, they have to implement a special form of math called floating point arithmetic. It’s from that term that we get the data type, float.
As you can see the error is in the degree of 10 to the minus 15 and will have no side effect on typical calculations.
As mentioned, the absence of fractions in binary creates the need for a special math module (typically a math co-processor embedded in the CPU or on the motherboard) to perform the massive amount of work needed to compute in decimal fractions or very small numbers. The other factor in the error is the amount of memory available to store a single number. Very minor on the whole given that most machines have 64 bits available, but still a factor.
When working with floats, expect to see (sometimes, not always) numbers such as above. All languages have the ability to round numbers, some even retain the number type.
print (round(z, 2))
>>> x = 19.93 >>> y = 20.00 >>> z = y - x >>> z 0.07000000000000028 >>> z = round(z, 2) >>> z 0.07 >>> type(z) <class 'float'> >>>