How to deal with floating point errors in R

后端 未结 3 1182
挽巷
挽巷 2021-01-06 13:59

Consider the following R function

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

which answers whether x is the square ro

3条回答
  •  执念已碎
    2021-01-06 14:55

    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
    

提交回复
热议问题