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
  • 2

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,322
  • 2
  • 16
  • 32
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
  • 1,904
  • 1
  • 17
  • 28
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
  • 36,219
  • 6
  • 36
  • 71