计算前 10 个斐波那契数
Compute the first 10 Fibonacci numbers
我需要在 matlab 中编写一个代码来计算
the first 10 Fibonacci numbers
但是我在这方面遇到了一些麻烦。我想到了使用此处定义的公式:
https://www.math.hmc.edu/funfacts/ffiles/10002.4-5.shtml
到目前为止我已经得到了这个
n = 0;
c = (((1+sqrt(5))/2)^n -((1-sqrt(5))/2)^2)/(sqrt(5));
while (n < 10)
disp(c)
n+1;
end
但正如您可能看到的那样,它是非常错误和不完整的。但我不确定还能做什么。教授希望我们编写正确的代码,这意味着我不能使用 fibonacci(n) 之类的东西。任何帮助将不胜感激:)
斐波那契数列似乎遵循 golden ratio, as talked about in some detail here。
这篇MATLAB File-exchange code用到了这个,写到这里,只写精华-
sqrt5 = sqrt(5);
alpha = (1 + sqrt5)/2; %// alpha = 1.618... is the golden ratio
fibs = round( alpha.^n ./ sqrt5 )
您可以将整数输入 n
以得到 Fibonacci Series
中的 nth
数字,或者输入数组 1:n
以获得整个系列。
请注意,此方法仅适用于 n = 69
。
记住斐波那契数的定义是什么:
fib(n) = fib(n-1) + fib(n-2);
你的公式对于计算前 10 个来说太过分了。只需将前 2 个设置为常量并使用你所知道的从中计算其他的(使用数组,因为一旦你计算了第三个你就可以计算第四个)。
我会为计算它的递归留下一些伪代码,你应该能够将这个想法转化为 matlab
let fib = [0,1,-1,-1...]
function Fibonacci(n){
if (fib[n] != -1) return fib[n] // If it exists already, we have it!
// otherwise, we can calculate it
// make sure to save the result so we can use it later if needed.
fib[n] = Fibonacci(n-1) + Fibonacci(n-2);
return fib[n];
}
fib_series = [0,1];
i = 3;
while length(fib_series) < 10
fib_series(i) = fib_series(i-1) + fib(i-2);
i = i+1;
end
我需要在 matlab 中编写一个代码来计算 the first 10 Fibonacci numbers 但是我在这方面遇到了一些麻烦。我想到了使用此处定义的公式:
https://www.math.hmc.edu/funfacts/ffiles/10002.4-5.shtml
到目前为止我已经得到了这个
n = 0;
c = (((1+sqrt(5))/2)^n -((1-sqrt(5))/2)^2)/(sqrt(5));
while (n < 10)
disp(c)
n+1;
end
但正如您可能看到的那样,它是非常错误和不完整的。但我不确定还能做什么。教授希望我们编写正确的代码,这意味着我不能使用 fibonacci(n) 之类的东西。任何帮助将不胜感激:)
斐波那契数列似乎遵循 golden ratio, as talked about in some detail here。
这篇MATLAB File-exchange code用到了这个,写到这里,只写精华-
sqrt5 = sqrt(5);
alpha = (1 + sqrt5)/2; %// alpha = 1.618... is the golden ratio
fibs = round( alpha.^n ./ sqrt5 )
您可以将整数输入 n
以得到 Fibonacci Series
中的 nth
数字,或者输入数组 1:n
以获得整个系列。
请注意,此方法仅适用于 n = 69
。
记住斐波那契数的定义是什么:
fib(n) = fib(n-1) + fib(n-2);
你的公式对于计算前 10 个来说太过分了。只需将前 2 个设置为常量并使用你所知道的从中计算其他的(使用数组,因为一旦你计算了第三个你就可以计算第四个)。
我会为计算它的递归留下一些伪代码,你应该能够将这个想法转化为 matlab
let fib = [0,1,-1,-1...]
function Fibonacci(n){
if (fib[n] != -1) return fib[n] // If it exists already, we have it!
// otherwise, we can calculate it
// make sure to save the result so we can use it later if needed.
fib[n] = Fibonacci(n-1) + Fibonacci(n-2);
return fib[n];
}
fib_series = [0,1];
i = 3;
while length(fib_series) < 10
fib_series(i) = fib_series(i-1) + fib(i-2);
i = i+1;
end