How to deal with floating point errors in R

后端 未结 3 1181
挽巷
挽巷 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:47

    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
    

提交回复
热议问题