我试图循环整数1:1000比较我用R函数创建的函数的结果。具体来说,我有:
floor.log2 = function(n) {
x = 1
i = 0
while (x <= n) {
x = 2*x
i = i + 1
}
print(i-1)
}
我想与之比较:
floor(log(n, base = 2))
我创建的每个比较循环最终打印每个索引1:1000 - 在没有R打印索引的情况下,在这些函数中比较1:1000的结果的简洁方法是什么?
答案 0 :(得分:0)
我会修改你写的现有函数:
floor.log2 = function(n) {
x = 1
i = 0
while (x <= n) {
x = 2*x
i = i + 1
}
return(i-1)
}
测试:
iter <- 100 # How long you would like to test for
vec1 <- c() # Container of your custom function
vec2 <- c() # Container for the comparison function
for(i in 1:iter) {
vec1[i] <- floor.log2(i)
vec2[i] <- floor(log(i, base = 2))
}
最后:
all(vec1 == vec2)