我正在尝试创建一个python循环,其中输出用作输入,直到输出和输入是等效的,这是我试图解决的语句:
1
----- = x
1+x
结果将比黄金比率(0.618034 ...)小1,我已经在纸上完成了它,并且需要大约20个循环以获得几个小数位的精确度。请告诉我用什么类型的python循环来解决这个问题?
答案 0 :(得分: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.)!
就检查值是否相同的逻辑而言,您需要具有某种阈值以用于精确目的(否则它将永远运行!),我建议您自己编写该检查模块化的方法。
希望这会有所帮助,如果您需要我发布更多实际代码,请告诉我(我尽量不泄露太多实际代码)。