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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With