PLotting Fibonacci Ratios against phi

4 次查看(过去 30 天)
Hiya so I've coded a fibonacci ratio finder which find the ratio between the nth fibonacci number and the one before it and found an n for which Fibrat(n) - phi< 10^-7. Now how di plot the error from n = 1:18 of Fibrat and phi against n?
Fibrat, golden ratio comparer and attempted plotting code
function r = Fibrat(n)
% Fibrat(n) gives the ratio of the n+1 th fibonacci number and the nth
% fibonacci number
F(1) = 1;
F(2) = 1;
for i = 3:n+1
F(i) = F(i-1)+F(i-2);
end
r = F(n+1)/F(n);
% Ratio comparer%
Phi = ((1 + sqrt(5))/2);
GR = 1;
i = 3;
while (abs(Phi - GR) > 10^(-7))
i = i+1;
GR = Fibrat(i);
end
format long
GR
i
%Plotting code%
f = [1 1];
fibratio = [1 1];
x = 1;
while x<=18
f(x+2) = f(x+1) + f(x);
x = x+1
fibratio(x+2) = f(x+2)/f(x+1);
end
plot(fibratio)

回答(1 个)

Rohit Pappu
Rohit Pappu 2021-1-27
Refactored version of your code
% Ratio comparer%
Phi = ((1 + sqrt(5))/2);
GR = 1;
i = 1;
error =abs(Phi-GR) % Initialize the error vector
while (abs(Phi - GR) > 10^(-7))
i = i+1;
GR = Fibrat(i);
error = [error abs(Phi-GR)]; % Append the current error to the error vector
end
% View various variables in long format
format long
GR
i
error
% Create a vector from 1:i and plot error against it
plot(1:i-1,error)
% Local function used by above code
function r = Fibrat(n)
% Fibrat(n) gives the ratio of the n+1 th fibonacci number and the nth
% fibonacci number
F(1) = 1;
F(2) = 1;
for i = 3:n+1
F(i) = F(i-1)+F(i-2);
end
r = F(n+1)/F(n);
end
Note - Local functions need to be defined after the driver code

类别

Help CenterFile Exchange 中查找有关 Data Types 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by