黄金比例函数习题

题目要求:

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/3
x
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值