2014-10-16 2 views
1

Я не могу понять, почему этот код возвращает значение False:Почему это вернуть Ложные

list_of_disks = [[170, 158, 470, 0.1], [135, 176, 410, 0.2], [100, 193, 350, 0.3], [170, 458, 470,  1.1]] 
def f1(pos): 
    for x in range(0, len(list_of_disks)): 
     if list_of_disks[x][3] == pos: 
      print list_of_disks[x+1][3] - 0.1, list_of_disks[x][3] 
      print list_of_disks[x+1][3] - 0.1 == list_of_disks[x][3] # Why is this False..? 
      break 

f1(0.2) 

Когда я распечатать 2 значения, они кажутся такими же ..? Надеюсь, кто-то может помочь мне здесь, спасибо!

+8

с плавающей точкой не может рассчитывать на то, что быть точным. –

+3

См. Учебник Python [«Плавающая точка: проблемы и ограничения»] (https://docs.python.org/2/tutorial/floatingpoint.html). См. Также [«Что каждый компьютерный ученый должен знать о арифметике с плавающей точкой»] (http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). –

+0

Я думаю, что точность здесь. –

ответ

1

Это потому, что 0,1 не может быть сохранена с помощью компьютеров (нет точного двоичного представления этого), поэтому 0.3-0.1 не то же самое, как от 0,2 до питона:

>>> 0.3-0.1==0.2 
False 

См http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/ для Мор подробной информации о точность с плавающей запятой.

Вы можете избежать этих ошибок, используя модуль Decimal, реализацию точной десятичной арифметики с плавающей запятой.

The purpose of this module is to support arithmetic using familiar 
"schoolhouse" rules and to avoid some of the tricky representation 
issues associated with binary floating point. The package is especially 
useful for financial applications or for contexts where users have 
expectations that are at odds with binary floating point (for instance, 
in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead 
of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected 
Decimal('0.00')). 
Смежные вопросы