-1

I am having trouble with iterating a function in Python.

I am trying to output values following:

enter image description here

This is the program:

def calculate(x):
    if x == 1:
      return 1.414
    elif x >= 2:
          a = (calculate(x-1)**2 + (1/(calculate(x-1)**2)))**(0.5)
          return (a)
          calculate (x-1)

For some reason, it only calculates output (a) for the input of x given. It will not print the values of input 1,2,3,4 ... x like I am trying to do.

rj1000
  • 3
  • 3
  • 3
    your `calculate (x-1)` is never getting called because you are returning the control flow using `return` before it's call – Moinuddin Quadri Mar 27 '18 at 10:01
  • 1
    `1.414` is not the square root of 1 – DeepSpace Mar 27 '18 at 10:04
  • @Moinuddin Quadri Sorry, am a beginner and am just learning. So is it better to use print (a) instead of return a in this case? – rj1000 Mar 27 '18 at 10:05
  • you are cheating: your square root implementation uses `x**0.5`... which **is** the square root... – hiro protagonist Mar 27 '18 at 10:07
  • @DeepSpace I don't think I made it clear; but my program is for a different recursive function using the square root of variables. The function I am building is for sqrt(x^2 + (1/(x^2)) – rj1000 Mar 27 '18 at 10:07
  • instead of `return` use `print` @rj1000 – Sanket Mar 27 '18 at 10:11
  • Thanks for your help. I replaced return with a print command. However, I am receiving an error in my code: TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'int' - Any ideas? – rj1000 Mar 27 '18 at 10:24
  • your recursive function calls itself with the same arguments 3 times... that means you are making the complexity here exponential. Also, generally recursion is an _alternative_ to iteration. Recursive functions recurse, they don't iterate. See https://stackoverflow.com/questions/15688019/recursion-versus-iteration – avigil Mar 28 '18 at 04:48

1 Answers1

0

Purely from code perspective, the code below runs -

def calculate(x):
    if x == 1:
        print(str(x) + " :: 1.414")
        return 1.414
    elif x >= 2:
        a = (calculate(x-1)**2 + (1/(calculate(x-1)**2)))**(0.5)
        print(str(x) + " :: " + str(a))
        return a
    else:
        print("Error")
        return None

However the recursion looks incorrect. See the method below which implements your function -

def cal(x):
    return ((x**2) + (1/(x**2)))**0.5 

for x=2, the recursive method returns - 1.5809955868425996, and the direct method returns - 2.0615528128088303 (which looks correct as function is adding a positive number to the absolute value of original number)

Aritesh
  • 1,985
  • 1
  • 13
  • 17
  • Hi Aritesh. Thanks for your advice. The reason that x = 2 yields 1.5801, is purely because it depends on x = 1, hence the recursion. The formula I posted in the question shows that x2 depends on x1. I just had an issue of printing all values of x in the recursion. – rj1000 Mar 27 '18 at 12:16