PLotting Fibonacci Ratios against phi

3 views (last 30 days)
Yuvraj Bhagotra
Yuvraj Bhagotra on 20 Jan 2021
Answered: Rohit Pappu on 27 Jan 2021
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)

Answers (1)

Rohit Pappu
Rohit Pappu on 27 Jan 2021
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

Tags

Community Treasure Hunt

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

Start Hunting!