title: How to avoid floating point errors?
body: <p>I was trying to write a function to approximate square roots (I know there's the math module...I want to do it myself), and I was getting screwed over by the floating point arithmetic. How can you avoid that?</p>
  
  <pre><code>def sqrt(num):
      root = 0.0
      while root * root &lt; num:
          root += 0.01
      return root
  </code></pre>
  
  <p>Using this has these results:</p>
  
  <pre><code>&gt;&gt;&gt; sqrt(4)
  2.0000000000000013
  &gt;&gt;&gt; sqrt(9)
  3.00999999999998
  </code></pre>
  
  <p>I realize I could just use <code>round()</code>, but I want to be able to make this really accurate. I want to be able to calculate out to 6 or 7 digits. That wouldn't be possible if I'm rounding. I want to understand how to properly handle floating point calculations in Python.</p>