Python's Numeric Value Trap, "How Deep?"

I am a pretty green programmer, and now I'm learning Python. I go back to chapter 17 in “Learn to Think Like a Computer Scientist” (classes and methods), and I just wrote my first doctrist who failed in some way, which I really didn't quite understand:

class Point(object):
    '''
    represents a point object.
    attributes: x, y
    '''

    def ___init___(self, x = 0, y = 0):
        '''
        >>> point = Point()
        >>> point.y
        0
        >>> point = Point(4.7, 8.2)
        >>> point.x
        4.7
        '''

        self.x = x
        self.y = y

The second tolerance for __init__fails and returns 4.7000000000000002 instead of 4.7. However, if I rewrite the doctrine with the print statement:

>>> point = Point(4.7, 8.2)
>>> print point.x
4.7

It is working correctly.

So, I read how Python saves a float, and now I understand that due to the binary representation of decimal numbers, the reason for the mismatch is that Python saves 4.7 as a string of 1 and 0, which is almost, but not quite equal to 4.7.

, "point.x" 4.7000000000000002, "print point.x" 4.7. Python , ""? ? (, , )? , ?

, , CS, Python, , , - , , , Python, / .

, , Python , , "a = 4.7"? , Decimal, , . , .

Edit: , Python 2.6 ( - NumPy Biopython)

+3
5
>>> point.x

repr , , str, ,

>>> print point.x

+4

, . . - point.x, point.x 4.7. ...

>>> point = Point(4.7, 8.2)
>>> point.x == 4.7
True

:

>>> point = Point(4.7, 8.2)
>>> eps = 2**-53 #get epsilon for standard double precision number
>>> -eps <= point.x - 4.7 <= eps
True

eps - . epsilon . .

EDIT: -eps <= point.x - 4.7 <= eps abs(point.x - 4.7) <= eps. , Python.

2: numpy, numpy eps, . eps = numpy.finfo(float).eps 2**-53, numpy. , numpy epsilon - , , 2**-52, 2**-53. , .

+3

:

a == b if abs(a-b) <= eps, where eps is the required precision.

eps , . - , ,

+2

, print :

In [1]: 1.23456789012334
Out[1]: 1.23456789012334 
In [2]: print 1.23456789012334
1.23456789012

, , Python:

In [3]: 4.7 == 4.7000000000000002
Out[3]: True

, float () , () . , , Python, . .

+1

.

- , Python.

+1

Source: https://habr.com/ru/post/1761001/


All Articles