如何处理R中的浮点错误 [英] How to deal with floating point errors in R

查看:80
本文介绍了如何处理R中的浮点错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下R函数

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

回答x是否为y的平方根.如果y是一个完美的正方形,则该函数的行为符合预期-is.sqrt(2,4)返回TRUE,而is.sqrt(3,4)返回FALSE.如果y不是理想平方,则会出现问题.例如,

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)

返回FALSE.可以通过计算来了解其原因

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

sqrt(2)^2 - 2

返回4.440892e-16.我对解决这个问题的第一个想法是在将x ^ 2与y进行比较之前将其取整,但是多少才合适呢?这甚至是推荐的方法吗? R中是否有处理浮点精度的标准方法?

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?

推荐答案

您可以在函数中使用all.equal,该函数测试两个对象是否'几乎'相等"

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

这篇关于如何处理R中的浮点错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆