0
x=(100+1.0/3)-100
y=1.0/3
z=1+1.0/3-1

x, y, z clearly have the same values mathematically, but

print(x==y)
print(x==z)
print(y==z)

generate False values for all.

Is there any way to make them equal to each other in python? I'm not quite sure why they're not considered same. I'm aware that rounding off would be the cause of it, but I'm not sure why that happens in different ways for x, y, z.

user98235
  • 830
  • 1
  • 13
  • 31
  • 4
    You can't compare floats directly due to floating point error. See: https://stackoverflow.com/questions/5595425/what-is-the-best-way-to-compare-floats-for-almost-equality-in-python – mVChr Jan 23 '19 at 21:05
  • Could also be a duplicate for https://stackoverflow.com/questions/588004/is-floating-point-math-broken. – SethMMorton Jan 23 '19 at 21:06
  • This is to do with how computers deal with what's called [floating point arithmetic](https://docs.python.org/2/tutorial/floatingpoint.html). – Adam Jan 23 '19 at 21:07

1 Answers1

0

You are running into floating point errors. The output of x, y, and z are:

>>> x
0.3333333333333286
>>> y
0.3333333333333333
>>> z
0.33333333333333326

You can see that they are clearly not equal.

See here for information about floating point errors.

Shane Fontaine
  • 2,431
  • 3
  • 13
  • 23