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)