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[
(* initialize variables *)
{curr=start,seq={start}},

(* main loop *)
Do[
(* compute the next value and append to the sequence *)
curr=func[curr];
AppendTo[seq,curr],

numIter (* repeat numIter times *)
];

(* return the sequence *)
seq
]

Iterate the ColVar function on some starting values. Keep track of the sequences you obtain.

makeSeq[colVar,5,50]

What do you observe? What do you wonder?

Write a module that detects when a trajectory repeats a value

Let's write a module that finds cycles. This is a version of Algorithm 3.12 in the text. Our version takes three parameters:

A function to iterate

A starting value

Optionally, a maximum number of iterations

findCycle[func_,start_,maxIter_:10000]:=Module[
(* initialize variables *) 
{seq={start} (* a list to store the sequence that we compute *),
next
},

(* main loop: repeat until we find a repeated value or maxIter iterations*)
Do[
(* compute the next iterate *)
next=func[seq[[-1]]];

(* check if we have seen this value before, if so, return the first repeating value *)
If[MemberQ[seq,next],
Return[next,Module]
];

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

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

findCycle[colVar,42,100]

makeSeq[colVar,42,100]

Finding items in a list

testList=Range[10]

MemberQ[testList,4]

MemberQ[testList,Pi]

Position[testList,4]

Position[testList,Pi]