我正在用 R 语言编写一个简短的程序,它根据两个起始数和一个停止数生成一个斐波那契数列。我决定使用递归而不是 for 循环来挑战自己并学到更多东西。但是,我需要生成一个向量,其中包含我生成的序列的每个数字。我在程序开始时创建了一个空向量来存放序列。问题在于,由于程序是递归的,因此每次调用该函数时该向量都会重置为空。我希望互联网上有一些关于如何继续使用递归但不重置为空向量的想法。
代码:
rec <- function (startN1, startN2, stopN2){
#the Fibonacci sequence is generate by starting with two numbers, adding them to generate a third.
# To continue generating numbers, you add the previous two values. Like so: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# startN1 is the first number you add, startN2 is the second, and stopN2 is the number before which you stop counting.
fibVals <-vector(mode = "numeric", length = 0) #fibVals is the vector of Fibonacci sequence numbers
if (startN2 < stopN2) { #checks to make sure the stop number has not been exceeded.
s <- sum(startN1, startN2) #generates the next number in the sequence
fibVals <- append(fibVals, s) #appends the new number to the Fibonacci Sequence vector
rec(startN2, s, stopN2) #recursive call
} #end if statement
else{
print(fibVals) #prints the Fibonnaci sequence the code (should) generate
}#end else statement
} #end function
最佳答案
您可以在 rec
的定义中定义 fibVals
向量,并将 fibVals
的当前值传递给下一个递归调用,例如:
rec <- function (startN1, startN2, stopN2, fibVals=vector(mode = "numeric", length = 0)){
#the Fibonacci sequence is generate by starting with two numbers, adding them to generate a third.
# To continue generating numbers, you add the previous two values. Like so: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# startN1 is the first number you add, startN2 is the second, and stopN2 is the number before which you stop counting.
#fibVals <-vector(mode = "numeric", length = 0) #fibVals is the vector of Fibonacci sequence numbers
if (startN2 < stopN2) { #checks to make sure the stop number has not been exceeded.
s <- sum(startN1, startN2) #generates the next number in the sequence
fibVals <- append(fibVals, s) #appends the new number to the Fibonacci Sequence vector
rec(startN2, s,stopN2,fibVals=fibVals) #recursive call
} #end if statement
else{
print(fibVals) #prints the Fibonnaci sequence the code (should) generate
}#end else statement
} #end function
> rec(1,1,100)
[1] 2 3 5 8 13 21 34 55 89 144
您方法的更紧凑版本:
rec2 <- function(fibs,stopN2) {
n <- length(fibs)
if (fibs[n] < stopN2) {
next.n <- sum(fibs[(n-1):n])
rec2(append(fibs,next.n), stopN2=stopN2)
} else
fibs
}
> rec2(c(1,1),100)
[1] 1 1 2 3 5 8 13 21 34 55 89 144
关于r - R中的语义错误,递归的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34439368/