Exploring a Variant of the Collatz Function

Math 242 Modern Computational Mathematics

Define a new function

Let’s modify the Collatz function by changing 3n+1 to 3n-1. That is, define ColVar(n)=3n-1 if n is odd, and ColVar(n)=(n/2) if n is even.

colVar[n_?OddQ]:=3n-1
colVar[n_?EvenQ]:=n/2

Here is a modified version of our makeSeq module from a week ago. This version takes three inputs: a function, a starting value, and a number of iterations; it returns a sequence of iterates.

makeSeq[func_,start_,numIter_]:=Module[{n=start,seq={start}},
Do[
(* compute the next value and append to the sequence *)
n=func[n];
AppendTo[seq,n],

{numIter} (* repeat numIter times *)
];

(* return the sequence *)
seq
]

Try out this module:

makeSeq[colVar, 10,40]

Example of sending a function to our module:

f[x_]:=x^2;
makeSeq[f,2,6]

What cycles emerge when iterating the ColVar function? How long is each cycle? What is the smallest number in each cycle?

How could you compute a trajectory from some starting value and stop when you identify a cycle?

Let's write a module that iterates a function and stops when it finds a repeated value.

findCycle[func_,start_,maxIter_:10000]:=Module[
{seq={start},n=start,pos},
(* main loop: iterate func from the starting value *)
Do[
(* compute the next value *)
n=func[n];

(* check if this value is repeated; if so, then quit and return the sequence *)
If[MemberQ[seq,n],
(* find position of where n first occurred *)
pos=Position[seq,n][[1,1]];
Return[seq[[pos;;]],Module]];

(* if we get here, then n is not a repeated value *)
AppendTo[seq,n]

,maxIter (* repeat maxIter times *)
];

(* if we get here, then we did not find a repeated value, so return False *)
False
]

Try this out:

findCycle[colVar,5]

findCycle[colVar,23]

findCycle[colVar,71]