-3

I am trying to make a python loop where the output is used as the input, until the output and input is equivalent, this is the statement that i am trying to solve:

  1
----- = x 
 1+x

The result will be 1 less than the golden ratio (0.618034...), i have done it on paper and it takes about 20 loops for a few decimal places of accuracy. Please tell me what type of python loop i would use to to solve this?

8
  • 6
    A while loop.
    – shashwat
    Commented Jun 14, 2013 at 17:51
  • @shashwat -- That's exactly the comment I was about to post ...
    – mgilson
    Commented Jun 14, 2013 at 17:51
  • 1
    I will not ask better questions if i don't know what is wrong with them. please explain the downvote and give constructive criticism.
    – kyle k
    Commented Jun 14, 2013 at 18:04
  • The bit that's wrong is that you haven't tried anything. There's all of two ways to loop in Python.
    – millimoose
    Commented Jun 14, 2013 at 18:07
  • @kylek Constructive criticism: show some effort. It's great that you have started by working the problem by hand. Now what have you done as far as code? Do you know the kinds of loops that Python has? If not, google will help you there. If you do, what have you tried in code? Commented Jun 14, 2013 at 18:09

1 Answer 1

1

So, based on what you're describing here, you want a while loop, since you want to keep doing something until a given condition becomes true.

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.)!

As far as the logic for checking whether the values are the same, you will need to have some sort of threshold value for precision purposes (otherwise it'll run forever!), and I would recommend writing that check in its own method for modularity's sake.

Hope this helps, and just let me know if you need me to post more actual code (I tried not to give away too much actual code).

1
  • I was going to use the rounding function as the threshold value.
    – kyle k
    Commented Jun 14, 2013 at 18:38

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.