Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with floating point errors in R

Consider the following R function

is.sqrt <- function(x, y){
  if(x^2 == y) TRUE
  else FALSE
}

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,

is.sqrt(sqrt(2), 2)

returns FALSE. The reason for this can be seen by calculating

sqrt(2)^2 - 2

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?

like image 560
Tim Hargreaves Avatar asked Jan 19 '26 04:01

Tim Hargreaves


2 Answers

you can use all.equal in your function, which "tests if two objects are 'nearly' equal"

is.sqrt <- function(x, y){
    isTRUE(all.equal(x^2,y)
}


 is.sqrt(sqrt(2), 2)
 # TRUE

 is.sqrt(sqrt(2), 3)
 # FALSE
like image 100
Daniel Avatar answered Jan 21 '26 16:01

Daniel


You can use the near function from dplyr, it has a built-in tolerance.

is.sqrt <- function(x, y) {
  near(x^2, y)
}

is.sqrt(sqrt(2), 2)

> TRUE
like image 34
Leonardo Siqueira Avatar answered Jan 21 '26 18:01

Leonardo Siqueira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!