I know that with binary representation it is not possible to exactly represent a floating-point number (and I also understand why 0.1 + 0.2 == 0.3 is false). Now here is where I got stuck while I tried to experiment with different cases of floating arithmetics:
Looking at the way decimal numbers are converted to binary format, I concluded that two numbers that have the same fractional part in decimal representation (eg: 0.3 and 1.3) will have the same fractional part once converted to binary form.
To test this out I tried the following codes in python:
print(f"{0.3:.20f}")
print(f"{1.3:.20f}")
0.29999999999999998890
1.30000000000000004441
I couldn't understand why the fractional parts were coming out to be different, so to understand the situation better I tried this:
print(f"{0.3:.20f}")
print(f"{1 + 0.3:.20f}")
print(f"{1.3:.20f}")
0.29999999999999998890
1.30000000000000004441
1.30000000000000004441
Question: Since 1 is not an approximate number (as it is possible to represent 1 in exact binary form as 2^0) so why does adding 1 change the fractional part of the number?
Furthermore, when we subtract 1 from 1.3 why is the resulting value not equal to 0.3
print(f"{1.3:.20f}")
print(f"{1.3 - 1:.20f}")
print(f"{0.3:.20f}")
1.30000000000000004441
0.30000000000000004441
0.29999999999999998890
My entire problem can be summarized in the following juxtaposition:
print(1 + .3 == 1.3)
print(0.3 == 1.3 -1)
True
False