'Why the counter does not work in this while loop?
In this code, the loop is still working to compute the ratio r according to the given condition of the absolute error until getting r=1.6180 at i=16, but here it gives the result at i=3 (initial i) which means the counter does not work. what is wrong here?
clc
clear
//funcprot(0)
function f=fib(n)
f(1)=1
f(2)=1
for i=3:n
f(i)=f(i-1)+f(i-2)
end
endfunction
//n=5
//disp(fib(n))
//compute golden ration
//compute golden ration
r0=0
r1=1 //ratio y2/y1
//err=r1-r0
i=3
while abs(r1-r0)>10^(-5)
r1=r0
r=fib(i)/fib(i-1)
i=i+1
end
//f(16)/
disp(r)
Thanks S. Gougeon. Also after clearing r1=r0 from the loop, I am getting the wrong result (r is the golden ratio of fibonacci sequence=(1+sqrt(5))/2).
clc
clear
//funcprot(0)
function f=fib(n)
f(1)=1
f(2)=1
for i=3:n
f(i)=f(i-1)+f(i-2)
end
endfunction
//n=5
//disp(fib(n))
//compute golden ration
//compute golden ration
r0=0
r1=1 //ratio y2/y1
//err=r1-r0
err=1
i=3
while abs(err)>10^(-5)
//r1=r0
r=fib(i)/fib(i-1)
err=r-r0
i=i+1
end
//f(16)/
disp(r)
Solution 1:[1]
In the while loop, setting r1=r0 yields r0-r0=0 for the next while condition (since r0 never changes), and so escapes the while condition and loop.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | S. Gougeon |
