估计 Python

Estimating in Python

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

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

所以我在 function 1 中输入了 use 2。估计 e 为 2.5,但 k 为 6 才能接近 2.522。

我要return 6.

我已经走到这一步了,但我不确定从那里去哪里。

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

我认为你需要两个独立的函数,不需要循环。

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