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
]

Examples:

makeSeq[colVar,13,50]

makeSeq[colVar,32,50]

Example not related to Collatz function:

f[x_]:=x^2

makeSeq[f,2,6]

What cycles appear when iterating the ColVar function?

Write a module that can detect when a ColVar trajectory enters a cycle.

Examples

Position[{5,8,4,3},4][[1,1]]

MemberQ[{5,8,4,3},4]

Let's write a module that detects when a trajectory repeats a value

findCycle[func_,start_,maxIter_:10000]:=Module[
{seq={start},n=start,p},
(* main loop: repeat until we find a repeated value or maxIter iterations*)
Do[
(* compute the next iterate *)
n=func[n];

(* check if we have seen this value before, if so, return the cycle *)
If[MemberQ[seq,n],
p=Position[seq,n][[1,1]];
Return[seq[[p;;]],Module]];

(* otherwise, append the value to the sequence *)
AppendTo[seq,n]
,maxIter];

(* if we get here, then we didn't find a repeated value *)
False
]

Try this out:

findCycle[colVar,13]

makeSeq[colVar,13,50]

findCycle[colVar,1]

findCycle[colVar,17]