gpt4 book ai didi

r - R 中 nextafter 功能的实现

转载 作者:太空宇宙 更新时间:2023-11-03 19:47:45 25 4
gpt4 key购买 nike

R 中是否有任何功能实现,以便可以从给定的 float 中获取下一个可表示的 float 。这类似于 nextafter C标准库中的函数。 number + .Machine$double.eps 等方案通常不起作用。

最佳答案

没有,但是有两种方法可以做到:

使用 C

如果您想要 nextafter() 的确切功能函数,您可以编写一个 C 函数作为该函数的接口(interface),以满足以下两个约束:

  • 函数没有返回值。所有工作都是作为“副作用”(改变参数的值)完成的。
  • 所有参数都是指针。在 R 中,即使是标量也是向量(长度为 1)。

然后该函数应该被编译为一个共享库:

R CMD SHLIB foo.c

用于类 UNIX 操作系统。可以使用 dyn.load("foo.so") 调用共享库.然后,您可以使用 .C() 从 R 内部调用该函数功能

.C("foo", ...)

从 R 调用 C 的更深入处理是 here .

使用 R

number + .Machine$double.eps是要走的路,但你必须考虑边缘情况,例如 x - y < .Machine$double.eps或者如果 x == y .我会这样写函数:

nextafter <- function(x, y){
# Appropriate type checking and bounds checking goes here
delta = y - x
if(x > 0){
factor = 2^floor(log2(x)) + ifelse(x >= 4, 1, 0)
} else if (x < 0) {
factor = 65
}
if (delta > .Machine$double.eps){
return(x + factor * .Machine$double.eps)
} else if (delta < .Machine$double.eps){
return(x - factor * .Machine$double.eps)
} else {
return(x)
}
}

现在,与 C 不同,如果你想检查整数,你可以在同一个函数中这样做,但你需要根据类型更改增量。

更新对于大于 2 的数字,前面的代码没有按预期执行。有一个因子需要乘以 .Machine$double.eps。使其足够大以导致数字不同。它与最接近的 2 加 1 的幂有关。您可以通过以下代码了解这是如何工作的:

n <- -100
factor <- vector('numeric', 100)
for(i in 1:n){
j = 0
while(TRUE){
j = j + 1
if(i - j * .Machine$double.eps != i) break()
}
factor[i] = j
}

关于r - R 中 nextafter 功能的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39754767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com