Note that there are some explanatory texts on larger screens.

plurals
  1. POPitfalls of number values in Python, "How deep?"
    primarykey
    data
    text
    <p>I'm a fairly green programmer, and I'm learning Python right now. I'm up to chapter 17 in "Learn to Think Like a Computer Scientist" (Classes and Methods), and I just wrote my first doctest that failed in a way I truly do not fully understand:</p> <pre><code>class Point(object): ''' represents a point object. attributes: x, y ''' def ___init___(self, x = 0, y = 0): ''' &gt;&gt;&gt; point = Point() &gt;&gt;&gt; point.y 0 &gt;&gt;&gt; point = Point(4.7, 8.2) &gt;&gt;&gt; point.x 4.7 ''' self.x = x self.y = y </code></pre> <p>The second doctest for <code>__init__</code> fails, and returns 4.7000000000000002 instead of 4.7. However, if I rewrite the doctest with a "print" statement as so:</p> <pre><code>&gt;&gt;&gt; point = Point(4.7, 8.2) &gt;&gt;&gt; print point.x 4.7 </code></pre> <p>It runs correctly.</p> <p>So I read up on how Python stores floats, and I now understand that, due to binary representation of decimal numbers, the reason for the discrepancy is that Python stores 4.7 as a string of 1s and 0s that almost but don't quite equal 4.7. </p> <p>But what I don't understand is why a call to "point.x" returns 4.7000000000000002 and a call to "print point.x" returns 4.7. Under what other circumstances will Python choose to round like it does with "print"? How does this rounding work? Can these trailing significant figures lead to errors in programming (aside from, obviously, failed doctests)? Can a failure to pay attention to rounding create dangerous ambiguity?</p> <p>Since this has to do with binary representation of decimal numbers, I'm sure that this is in fact a general CS issue and not one specific to Python, but what I really need to know right now is what I can do, specifically as a Python programmer, to avoid any related issues and/or bug infestations.</p> <p>Also, for bonus points, is there some other way that Python can store floating point numbers aside from the default activated by a line like "a = 4.7"? I know there's the Decimal package, but I'm not totally sure how it works. Honestly, all of this dynamic typing stuff confuses me sometimes.</p> <p><strong>Edit:</strong> I should specify that I'm using Python 2.6 (at some point I want to use NumPy and Biopython)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload