title: How to deal with floating point errors in R
body: <p>Consider the following R function</p>
  
  <pre><code>is.sqrt &lt;- function(x, y){
    if(x^2 == y) TRUE
    else FALSE
  }
  </code></pre>
  
  <p>which answers whether x is the square root of y. If y is a perfect square, the function behaves as expected - is.sqrt(2,4) returns TRUE and is.sqrt(3,4) returns FALSE. The problem occurs if y is not a perfect square. For example,</p>
  
  <pre><code>is.sqrt(sqrt(2), 2)
  </code></pre>
  
  <p>returns FALSE. The reason for this can be seen by calculating</p>
  
  <pre><code>sqrt(2)^2 - 2
  </code></pre>
  
  <p>which returns 4.440892e-16. My first thought on how to solve this would be to round x^2 before comparing it to y but by how much is appropriate? And is this even a recommended way? Is there a standard method in R to deal with floating point precision?</p>