用Python估算

时间:2018-10-02 03:25:04

标签: python tail-recursion

我正在尝试编写一个python函数,该函数将给我返回数字k的第一个值,该数字将function 2 >= function 1

function 1(p) => 1 + 1/1! + 1/2! + 1/p!
function 2(k) => (1 + 1/k)^k

因此,我在2中输入了function 1。估计e等于2.5,但要使k接近6,即2.522。

我想退回6。

我走的很远,但是我不确定从那里去哪里。

for x in range(p):
    factorial(x):
        if x == 0:
            return 0
        else:
            return x * factorial(x-1)
result = 1 + 1/factorial(p)

1 个答案:

答案 0 :(得分:1)

我认为您需要两个单独的函数,并且不需要循环。

def factorial(x):
    if x in {0, 1}:
        return 1  # This needs to be 1, otherwise you multiply everything by 0
    else:
        return x * factorial(x-1)

def summ(p):
    if p == 0:
        return 1
    elif p == 1:
        return 2
    else:
        return 1/factorial(p) + summ(p-1)

关于其余的问题,我认为这会有所帮助

def f2(k):
  return 1 if k == 0 else (1 + 1/k)**k

max_iter = 10  # TODO: increase
k = 0
delta = 0.000001
while max_iter > 0:
  f1_result = summ(k)
  f2_result = f2(k)

  check = f1_result <= f2_result
  print("k={}:  {:6.8f} <= {:6.8f} == {}".format(k, f1_result, f2_result, check))

  k += 1
  max_iter -= 1

  # if check:
  #    break

# TODO: Check if difference is within acceptable delta value

输出

k=0:  1.00000000 <= 1.00000000 == True
k=1:  2.00000000 <= 2.00000000 == True
k=2:  2.50000000 <= 2.25000000 == False
k=3:  2.66666667 <= 2.37037037 == False
k=4:  2.70833333 <= 2.44140625 == False
k=5:  2.71666667 <= 2.48832000 == False
k=6:  2.71805556 <= 2.52162637 == False
k=7:  2.71825397 <= 2.54649970 == False
k=8:  2.71827877 <= 2.56578451 == False
k=9:  2.71828153 <= 2.58117479 == False

从较大的数字开始,此检查仍然在k=996失败,并引发了递归错误。

k=996:  2.71828183 <= 2.71691848 == False
Traceback (most recent call last):
  File "python", line 22, in <module>
  File "python", line 13, in summ
  File "python", line 5, in factorial
  File "python", line 5, in factorial
  File "python", line 5, in factorial
  [Previous line repeated 992 more times]
RecursionError: maximum recursion depth exceeded

因此,如果您使用循环而不是递归编写了阶乘函数,将会很有帮助。


修改

我想我理解你现在想要得到的东西

in1 = int(input("value 1:"))
v1 = summ(in1)
v2 = 0
max_iter = 50  # Recursion execution limit
while f2(v2) <= v1 and max_iter > 0:
  v2 += 1
  max_iter -= 1
print(v2)

输出

value 1: <enter 2>
6