简体   繁体   English

[Python]我的递归有什么问题?

[英][Python]what's wrong with my recursions?

I want to performe 我想表演

  [√(1/2+1/2*√1/2)]  ---------(P1)
  [√(1/2+1/2*√(P1)]  ----------(P2)
  [√(1/2+1/2*√(P2)]  
  etc.

to find out the P(nth)term 找出P(nth)项

I have this for now 我现在有这个

from math import *

n=eval(input('fjeowijo'))
i=sqrt(1/2+1/2*(sqrt(1/2)))

def P(n):
  for i in range(n):        
      g=sqrt(1/2+1/2*i)
      i=sqrt(1/2+1/2*i)
      print(g)

P(n)

When I enter 1 for n, the result is 0.7071067811865476, which is only equal to the part " sqrt(1/2) ". 当我为n输入1时,结果为0.7071067811865476,仅等于部分“ sqrt(1/2)”。 Why? 为什么?

def P(n):
  i = 0
  g = sqrt(0.5+.5*sqrt(0.5)
  while(i < n):
    g = sqrt(0.5+0.5*g)
    print(g)

Could it be what you're looking for ? 可能是您要找的东西吗?

In case you want to make it recursive do 如果您想使其递归

def P(n):
    if n <= 0:
        return 0.5
    else:
        return sqrt(0.5*(1+sqrt(P(n-1))))

which works out as 算出来

>>> P(1)
0.9238795325112867
>>> P(2)
0.9902490907008235
>>> P(3)
0.9987774031336784
>>> P(4)
0.9998471169658009

As @JoshRomRock points out, python generally limits the maximum depth of the recursion (the default max depth is platform-dependent). 正如@JoshRomRock指出的那样,python通常会限制递归的最大深度(默认的最大深度取决于平台)。 In case of CPython, the default limit is 1000. 对于CPython,默认限制为1000。

In case you want to alter such limit do: 如果您想更改此限制,请执行以下操作:

import sys
sys.setrecursionlimit(5000)

Note: in this case, the precision offered by the floating point representation may well be the biggest hurdle to the calculation. 注意:在这种情况下,浮点表示形式提供的精度可能是计算的最大障碍。 Please see the official docs for further info on what to expect using floats. 请参阅官方文档,以获取有关使用浮点数的更多信息。

Second note: in case the P function is going to be used several times and/or in multiple points of the code of a program, as a library function, it would make sense to implement it using Memoization . 第二个注意事项:如果P函数要多次使用和/或在程序代码的多个点使用, 则应将其作为库函数使用Memoization实现。 Please see here for a few examples in python. 在此处查看python中的一些示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM