0

I'm writing a program that solves a system of lineair equations. I need to run some iterations in order to see my objective value improving. I first wrote the program with writing print functions at the bottom of my file. So I did the iterations myself basically. I now want to write the number of iterations as an imput argument for the function.

I tried working with while and for loops but that did not seem to work for me. So now I tried the format as you can see below. I have not put my entire program here, but just the basic structure of what it does.

def function(A,x,c,iter):
    if iter == 0:
        return x
    else:
        A = 1/2 * A
        c = 1/2 * c
        x1 = 1/2 * x

        iter = iter - 1

        function(A,x1,c,iter)

When I have iter = 0, it gives me the immediate value of x. But when iter > 0 I get 'None' back... Can anyone explain why it does this and help me fix my program? Thanks!

David W.
  • 107
  • 3
  • Common mistake - you don't return the result of the recursive call. – meowgoesthedog May 30 '19 at 14:14
  • Prefer a simple loop to recursion; `for _ in range(iter): A, x, c = A/2, x/2, c/2; return x`. – chepner May 30 '19 at 14:17
  • 1
    Possible duplicate of [Why does my recursive python function return None?](https://stackoverflow.com/questions/17778372/why-does-my-recursive-python-function-return-none) – N Chauhan May 30 '19 at 14:20

3 Answers3

2
def function(A,x,c,iter):
    if iter == 0:
        return x
    else:
        A = 1/2 * A
        c = 1/2 * c
        x1 = 1/2 * x

        iter = iter - 1

        return function(A,x1,c,iter)

You just didn't return the value of the else and Python functions return None when there is not return statement.

Tom Ron
  • 5,906
  • 3
  • 22
  • 38
0

Add a return in the last line so the value is returned after executing the function: return function(A,x1,c,iter)

Marc Sances
  • 2,402
  • 1
  • 19
  • 34
0

As a for loop it would look like:

def function(A,x,c,iterN):
    for _ in range(iterN)
        A = 1/2 * A
        c = 1/2 * c
        x = 1/2 * x
    return x

As a note, do not use iter for variable naming since it is a built-in python function.

Netwave
  • 40,134
  • 6
  • 50
  • 93