-3

我正在尝试创建一个 python 循环,其中输出用作输入,直到输出和输入相等,这是我要解决的语句:

  1
----- = x 
 1+x

结果将比黄金比例(0.618034 ...)小1,我已经在纸上完成了,它需要大约20个循环才能获得小数点后几位的精度。请告诉我我会用什么类型的 python 循环来解决这个问题?

4

1 回答 1

1

因此,根据您在此处描述的内容,您需要一个 while 循环,因为您想继续做某事,直到给定条件变为真。

lastOutput = 0; # an arbitrary starting value: the last output value 
                # needs to be shared between loop cycles, so its 
                # scope must be outside the while loop

startingValue = # whatever you start at for input
finished = False # flag for tracking whether desired value has been reached
while (!finished):
    # body of loop:
    # here, you need to take lastOutput, run it through the 
    # function again, and check if the new output value is the
    # same as the input that created it. If so, you are done,
    # so set the flag to True, and note that the correct value is now stored in lastOutput
    # If not, set the new output as lastOutput, and go again!

# ...and now finish up with whatever you want to do now that you've 
# found the value (print it, etc.)!

至于检查值是否相同的逻辑,您需要有某种阈值以达到精确目的(否则它将永远运行!),我建议在其自己的模块化方法中编写该检查清酒。

希望这会有所帮助,如果您需要我发布更多实际代码,请告诉我(我尽量不泄露太多实际代码)。

于 2013-06-14T18:04:52.807 回答