1

I need to build a python code for the following equation.

Question

As I understood this equation has only 4 iterations and until it becomes true need to recall the function again. But when recalling the function the value which use to store the number of iterations will be lost.

The code which I have write is this.

def answer(z):

    for i in 5:
        if i == 4:
            zn =  z + 1/z
        else:
            y = 1 / z + zn
            
    return y

z = float(input("Enter value for Z : "))

print("The Y Value is   : %.4f" %answer(z))

I need to know to build the code for this equation.

Haree.H
  • 53
  • 7
  • 1
    add anther parameter to `answer` ( e.g. `answer(z, n)` ), and use it as current number of iteration. – ymonad Jul 25 '21 at 04:09

2 Answers2

2

You could use the following. Your algorithm needs to update the denominator several times.

def answer(z, n=4):
    z_den = z
    for i in range(n):
        z_den = z + 1/z_den
    final_answer = 1 / z_den
    return final_answer
GabrielP
  • 777
  • 4
  • 8
  • Thank you so much for your answer. But `n` value should be equal to 3 (`n=3`). Because the final step is handled by the `final_answer`. – Haree.H Aug 08 '21 at 15:01
0

I think you could utilize recursion for this:

def answer(z, y = 0, n = 1):
    if n == 1:
        y = z + 1/z
        answer(z, y, n+1)
    elif n > 1 and n < 4:
        y = z + 1/y
        answer(z, y, n+1)
    else:
        print(1/y)

Where

answer(2) -> 0.4137931034482759
answer(10) -> 0.09901951266867294
answer(15) -> 0.0663729751856689

Mason
  • 229
  • 1
  • 7