How to determine the period of a function

if I have a function A that can apply a certain rule to a given matrix to create another matrix, which I call it the next state of the original matrix, also the function can determine the final state of the matrix by a given time N (apply the origin rule and reapply the rule in the next state of the matrix start and apply the rule of applying the rule ... for N times).

So, suppose for a given matrix, apply the rule to it 5 times, and the final matrix becomes the same as the origin matrix, and we call this matrix period 5.

And I have another function B, how can I force function B to determine the period of the given function under the same rule of function A and return the period? I just don't know how to start doing this .. Thanks in advance.

def functionA(origin_matrix,N_times):
   #apply rule on the origin_matrix to generate another matrix which is the next sate of it.
   #apply rule on origin_matrix for N_times
   return the_final_matrix

def functionB(origin_matrix):
   #determine the period of the the origin_matrix.
   return period

      

+1


source to share


1 answer


Use a for loop or a while loop with a temporary result and a counter. The latter method is the most effective (in general).

Simple version, in pseudocode:

iterations = 0;
tmp = origin_matrix;

do
    tmp = operation(tmp);
    iterations += 1;
while tmp != origin_matrix;

return iterations;

      

EDIT: you can also use a simple construct:



while True:
    tmp = operation(tmp)
    iterations += 1

    if tmp == origin_matrix:
        break  # Or you could return here.

      

EDIT: This was for feature B. I didn't know they were separate questions. For this example, operation (x) = functionA (x, 1).

For function A, you will most likely use a for loop. Pseudocode:

matrix = origin_matrix

for i in range(N_times):
    matrix = operation(matrix)

return matrix

      

+6


source







All Articles