Yesterday I was wondering how floats are handled in a computer and what they look like in binary... I learnt about the single-precision floating-point and I tried to see the limit of that format...
I first wrote this little Python (3.4) script
a,b = 1,1 while (a+b)-a-b == 0: a*=2.0 while (a+b)-a-b != 0: b+=1.0 print(a,b)
I wanted to see what specific exponent value of a could be create a lack of precision in the result (a+b)-a-b, and if increasing the value of b could correct it.
The output was :
I noticed that 2^53 = 9007199254740992.0 and I though it was a bit disturbing : the binary representation of 53 is 110101, and this really doesn't look like any specific value...
The "2.0" let me a little less sceptical, as you just have to add 1 to increase the exponent value of b. It made more sense, but I realised I couldn't explain it properly too.
I modified my script to see the actual binary value of everything I was doing :
import struct def binary(f): return str(bin(struct.unpack('!i',struct.pack('!f',f)))).replace('0b', '') def status(a,b): return binary(a),binary(b),binary(a+b),binary(-a),binary(-b),binary(-a-b),binary((a+b)-a-b) a,b = 1,1 while (a+b)-a-b == 0: a*=2.0 print(status(a,b)) print("\n") while (a+b)-a-b != 0: b+=1.0 print(status(a,b)) print(a,b)
But what I saw didn't help me. I can't figure out why the lack of precision happens at that specific value of a, and why increasing b just once would correct it.
Could anyone help me understanding this ?
(I apologize in advance for my really poor English)