为什么计数器在循环时不起作用?
在此代码中,循环仍在努力根据绝对错误的给定条件计算比率r,直到在i = 16处获得r = 1.6180,但在这里给出了i = 3(初始i)的结果,这意味着计数器不起作用。这里怎么了?
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)
谢谢S. Gougeon。同样,在从循环中清除R1 = R0之后,我得到了错误的结果(R是fibonacci序列的黄金比率=(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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在段循环中,设置r1 = r0会在下一个条件下产生R0-R0 = 0(因为R0永远不会更改),因此可以逃脱时条件和循环。
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.