R 中的 Collat​​z 猜想

2024-01-18

我仍然主要向我自己(和我的学生)教授一些 R。

下面是 Collat​​z 序列在 R 中的实现:

f <- function(n)
{
    # construct the entire Collatz path starting from n
    if (n==1) return(1)
    if (n %% 2 == 0) return(c(n, f(n/2)))
    return(c(n, f(3*n + 1)))
}

调用 f(13) 我得到 13, 40, 20, 10, 5, 16, 8, 4, 2, 1

但请注意,这里向量的大小是动态增长的。此类举动往往会导致代码效率低下。有更高效的版本吗?

在Python中我会使用

def collatz(n):
    assert isinstance(n, int)
    assert n >= 1

    def __colla(n):

        while n > 1:
            yield n

            if n % 2 == 0:
                n = int(n / 2)
            else:
                n = int(3 * n + 1)

        yield 1

    return list([x for x in __colla(n)])

我找到了一种无需先验指定向量维度即可写入向量的方法。因此解决方案可以是

collatz <-function(n)
{
  stopifnot(n >= 1)  
  # define a vector without specifying the length
  x = c()

  i = 1
  while (n > 1)
  {
    x[i] = n
    i = i + 1
    n = ifelse(n %% 2, 3*n + 1, n/2)
  }
  x[i] = 1
  # now "cut" the vector
  dim(x) = c(i)
  return(x)
}

我很好奇 C++ 实现是如何通过Rcpp将与您的两种基本 R 方法进行比较。这是我的结果。

首先我们定义一个函数collatz_Rcpp返回给定整数的 Hailstone 序列n。 (非递归)实现改编自罗塞塔代码 https://rosettacode.org/wiki/Category:C%2B%2B.

library(Rcpp)
cppFunction("
    std::vector<int> collatz_Rcpp(int i) {
        std::vector<int> v;
        while(true) {
            v.push_back(i);
            if (i == 1) break;
            i = (i % 2) ? (3 * i + 1) : (i / 2);
        }
        return v;
    }
")

我们现在运行一个microbenchmark使用您的基础 R 和Rcpp执行。我们计算前 10000 个整数的 Hailstone 序列

# base R implementation
collatz_R <- function(n) {
    # construct the entire Collatz path starting from n
    if (n==1) return(1)
    if (n %% 2 == 0) return(c(n, collatz(n/2)))
    return(c(n, collatz(3*n + 1)))
}

# "updated" base R implementation
collatz_R_updated <-function(n) {
  stopifnot(n >= 1)
  # define a vector without specifying the length
  x = c()
  i = 1
  while (n > 1) {
    x[i] = n
    i = i + 1
    n = ifelse(n %% 2, 3*n + 1, n/2)
  }
  x[i] = 1
  # now "cut" the vector
  dim(x) = c(i)
  return(x)
}

library(microbenchmark)
n <- 10000
res <- microbenchmark(
    baseR = sapply(1:n, collatz_R),
    baseR_updated = sapply(1:n, collatz_R_updated),
    Rcpp = sapply(1:n, collatz_Rcpp))

res
#         expr        min         lq       mean     median         uq       max
#        baseR   65.68623   73.56471   81.42989   77.46592   83.87024  193.2609
#baseR_updated 3861.99336 3997.45091 4240.30315 4122.88577 4348.97153 5463.7787
#         Rcpp   36.52132   46.06178   51.61129   49.27667   53.10080  168.9824

library(ggplot2)
autoplot(res)

(非递归)Rcpp实现似乎比原始(递归)基本 R 实现快 30% 左右。 “更新的”(非递归)基 R 实现明显慢于原始(递归)基 R 方法(microbenchmark在我的 MacBook Air 上大约需要 10 分钟才能完成,因为baseR_updated).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

R 中的 Collat​​z 猜想 的相关文章

随机推荐