Wrong Decimal Output

17 views
Skip to first unread message

SarahC5 GoRonix

unread,
Mar 8, 2020, 4:26:50 PM3/8/20
to spyder
Hi, my name is Veronica, I am new to Python programming.
I am using Spyder, and here is what is in my code.  It's giving
me the wrong output:

EDITOR___
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = float(num1) + float(num2)

print(result)

CONSOLE_____________
Enter a number: 4.4

Enter another number: 2.2
6.6000000000000005

QUESTION________________
Why is this the output?  It's supposed to be 6.6
Why is it adding those zeros and the five at the end?

WRONG OUTPUT.PNG

bcolsen

unread,
Mar 9, 2020, 1:01:00 PM3/9/20
to spyder
This is because the computer isn't able to exactly store 2.2 or 4.4 in a binary floating point with a limited number of bits.

This is similar to you trying to express 1/3 as a decimal and doing math with that (0.3333+0.3333+0.3333 = 0.9999 ≠ 1).

Remember computers aren't smarter than you, just a lot faster.

Philip Yip

unread,
Mar 9, 2020, 1:01:00 PM3/9/20
to spyder
Hi Veronica

Conceptually what you have is similar to the following:
(1/3)+(1/3)=(2/3)
This is conceptually easy to write on a piece of paper in fraction form but in decimal (base10) form you need to write it out as an infinitely long series of numbers to store it precisely (which you cannot do):
1/3=0.3333333...
In decimal you have 10 bits which we associate with the following characters to store a number (0,1,2,3,4,5,6,7,8,9).

You essentially have the same issue with your code. Just to simply it typing in:
0.4+0.2
Also gives the same result:
0.6000000000000001

In binary you only have 2 bits or if you rather only 2 characters to store a number (0,1). Numbers in a computer that are stored in binary (base 2) have the same issue as 1/3 in decimal in that it cannot be precisely stored and must be rounded at the end. Like the length of a piece of paper for writing down a number, the memory that a computer has to store a number is finite.

Binary notation can be thought of as converting a number to decimal form using scientific notation but with only 2 characters opposed to 10.
For more details about the underlying principles of this problem look up float16 and the classical example 0.1.
The binary representation of 0.1 is recurring:
0.1 (base 10) = 0.000110011001100110011... (base 2)

To address this in your code, use the round function to round your value. For example:
round((0.2+0.4),2)=0.6
Will round to 2 decimal places.
round((0.2+0.4),16)=0.6000000000000001
Will round to 16 decimal places giving you the same value as before.

Philip

Michiel Karrenbelt

unread,
Mar 9, 2020, 1:01:00 PM3/9/20
to spyder
Reply all
Reply to author
Forward
0 new messages