Report r_n and n when |r_n − r_n−1|< 10−9 (while-loop).

1 回表示 (過去 30 日間)
LILIA VERGARA
LILIA VERGARA 2023 年 1 月 20 日
回答済み: Dyuman Joshi 2023 年 1 月 20 日
I was asked to create a while loop for Fibonacci sequence
with initial values: Fn= Fn1 + Fn2,
F0 = 2 and F1 = 3
note r_n= Fn+1/Fn
It wants me to report r_n and n when |rn−rn−1|< 10−9 (while-loop)
Code created:
fib_first = 2;
fib_second = 3;
fib_all = zeros(n, 1);
fib_all(2) = fib_first;
fib_all(3) = fib_second;
n=1:100
fib_all(ii) = fib_all(ii-1)+fib_all(ii-2)
while abs(r_n - r_n-1) < 10^-9
end
I am having a hard time understanding what I am doing wrong. I do not feel confident with this code.
  2 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 1 月 20 日
Is r(n)
%1
F(n+1)/F(n)
%2
(F(n)+1)/F(n)
%3
F(n)+(1/F(n))
LILIA VERGARA
LILIA VERGARA 2023 年 1 月 20 日
Hi- r(n) is %1

サインインしてコメントする。

回答 (1 件)

Dyuman Joshi
Dyuman Joshi 2023 年 1 月 20 日
You have to update the values inside the while loop. One way to do is
F=[2 3 5];
%defining rn = F(n+1)/F(n)
r=F(2:3)./F(1:2);
n=2;
while abs(diff(r))>=1e-9
F=[F(2:3) F(2)+F(3)];
r=F(2:3)./F(1:2);
n=n+1;
end
F
F = 1×3
28657 46368 75025
n
n = 22
rn=r(end)
rn = 1.6180

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by