+ 5
why 1.2+1.4 is equal to 2.59999 in python
3 Respuestas
+ 9
It is a kind of 'math problem'.
Do you ever trying to convert a decimal to a binary by your self?
Computer can only do binary calculation in CPU.
Some decimals can be convert into binary easily. For example:
1.5(decimal)=1*2^0+1*2^(-1)=1.1(binary)
But others are more complex. For example:
1.2(decimal)=1*2^0+0*2^(-1)+0*2^(-2)+1*2^(-3)+1*2^(-4)+0*2^(-5)+0*2^(-6)+1*2^(-7)+1*2^(-8)+......because of binary is limited in 2^x, this cannot be displayed finitely but a infinitely repeated digit=1.00110011001100110011... (binary)
Now the question is simple.
Python or other software cannot deal with a infinite decimal (in general) so they only calculate several digits, the result may become a weird number.
(like we all know 1/3+2/3=1 but if you type 1/3 in calculator it may display 0.33333333, similarly 2/3 become 0.66666666 so the result will be 0.99999999 but not 1)
Summarizing:
1. computer always convert decimal to binary
2.like 1/3=0.3333...when converting decimal into binary, some can be infinite.
3.general calculator aill only calculate limited digit so the rest may lost and the result may got wired.
+ 2
Floats often have a weird behaviour. They often either remove or add 10**(-15) to the end. I don't know why, but I think C language has something to do with it.