1

I get two different amount for machine epsilon when I use below python codes, what is the reason?

i=1
while i+1 != 1 :
    m=i
    i=i/2
print(m)

and

i=1
while i != 0 :
    m=i
    i=i/2
print(m)

dividing the output of the first code by 2 is not equal to zero, but dividing output of the second code by 2 is zero!

  • 2
    You are assuming `i + 1` is exact; that's not true for numbers very close to 0, because adding one "steals" a bit of precision away from the fractional part. – chepner Feb 23 '20 at 22:25

2 Answers2

2

If you add a count to each loop you'll see that the second iterates a lot more times than the first

i=1
count = 0
while i+1 != 1 :
    count += 1
    m=i
    i=i/2

print(count)

53

i=1
count = 0
while i != 0 :
    count += 1
    m=i
    i=i/2

print(count)

1075

The reason for this is floating point maths, and you shouldn't try to explicitly check a floating point number for equality with another. See What is the best way to compare floats for almost-equality in Python? for a possible solution, and Is floating point math broken? for more information on floats.

Sayse
  • 42,633
  • 14
  • 77
  • 146
0

After Searching in python documentation I found this. Python shows 16 digits of a float number, if it is more than 16 digits python rounds it. It doesn't mean the minimum number that can be represented by python is 10^-16. It can represent 0.00000000000000000001234567887654321 but not 1.12345678876543211