黄金比例函数习题

来源:互联网 发布:管家婆软件免费版视频 编辑:程序博客网 时间:2024/04/28 19:30

题目要求:

The definition of a Fibonacci sequence is like this:
- F(0) = 0
- F(1) = 1
- F(n) = F(n-1) + F(n-2)

Now let’s define G(n) = F(n)/F(n+1).

Golden ratio is the limit of G(n) when n approaches infinity.

With all the above information, we have a way to estimating golden ratio g:

Find the first n that matches |G(n+1) - G(n)| < t, where t is the
precision threshold, then the corresponding G(n) is considered as
the estimated value of golden ratio.

解题思路:

  1. 这里面需要考虑的首先是给出怎样的输入,得到怎样的输出。

  2. 根据题目要求,输入只有一个数,就是t,输出为找到的第一个满足条件的n。

  3. 然后就需要考虑时间复杂度和空间复杂度。所以有序只需要输出一个数n,那么是不需要把整个数列作为G(n)函数的输出,只需要一个数,然后通过这个数在G(n)中的位置输出n

这里面需要注意python2和python3的区别,在python3中,一个数除以另一个数如果无法整除会输出浮点数

x = 1/3x
0.3333333333333333
def fibo01(n):    x, y = 0, 1    while(n):        x,y,n = y, x+y, n - 1    return x# 构建斐波那契额数列,输入一个正整数num,返回含有num个数的斐波纳契数列def fibo(num):    numList = [0,1]    for i in range(num - 2):        numList.append(numList[-2] + numList[-1])    return numList # 返回一个数列# 构建G数列,输入一个数num,返回第num个G数列中的数def G(num):    numList = [0, 1]        for i in fibo(num):        numList.append(fibo(num)[-2]/fibo(num)[-1])    return numList[num] # 返回一个数,作为下面判断条件的输入# 构建函数find_first_n(t), 输入t,t为大于0小于1的浮点数,输出第一个满足条件的 |G(n+1) - G(n)| < t 的n值def find_first_n(t):    i = 0    while abs(G(i+1)-G(i)) > t:        i += 1    return i
find_first_n(0.000000000001)
31

注: python中科学计数法的表示

10**5
100000
10 ** -5
1e-05
10 ** (-5) == 0.00001
True
原创粉丝点击