[Scilab-users] Visualising Collatz sequences

Lester Anderson arctica1963 at gmail.com
Wed Apr 13 17:36:06 CEST 2022


Hello all,

I have prepared a code to generate Collatz sequences based on the even
(n/2) and odd ((3n+1)/2) rules.

clear

function [ns, seq] = collatz(n)
// Reference: https://en.wikipedia.org/wiki/Collatz_conjecture
//ns =number of steps; seq=Collatz sequence
seq(1) = n;
// Position an index on the next element of the sequence
i = 2;

// Repeat the iteration until you find a 1
while seq(i-1) ~= 1
    // Use modulo to define even/odd numbers
    if modulo(seq(i-1), 2) == 0
        // Step taken if even
        seq(i) = seq(i-1)/2;
    else
        // Step taken if odd
        // seq(i) = 3*seq(i-1) + 1 // "3n+1 Collatz"
        seq(i) = (3*seq(i-1) + 1)/2; // "shortcut form Collatz"
    end
    // Increment index
    i = i+1;
end
// Find the length of the sequence
ns = length(seq);
endfunction

n = input('Enter a positive integer: ')
tic()

for  i = 1:n
   [nsi, seqi] = collatz(i);
   ns(i) = nsi;
   seq(1:nsi, i) = seqi;
end

// Find maxima in each Collatz sequence
peak_values = max(seq, 'r')

t=toc()
mprintf('Elapsed time: %4.8f\n',t)

What I would like to try is apply a further rule to generate a plot
based on the Collatz sequences using left/right angular turn depending on
whether the number is odd or even, going in reverse (starting at 1) and
branching out.

I can easily define the odd/even numbers in the sequence (modulo), but not
sure how to
apply the angle rotation for the graphic plot. Any pointers would be
helpful.

Attached an example image by way of reference.

On a secondary point, the Collatz conjecture can be applied to negative
values, but would be interested to know how the code has to be tweaked. If
you stick a negative value in the code as is, it gets stuck in a loop.

Thanks
Lester
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.scilab.org/pipermail/users/attachments/20220413/594fb2e3/attachment.htm>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Collatz_path_plot.png
Type: image/png
Size: 67094 bytes
Desc: not available
URL: <https://lists.scilab.org/pipermail/users/attachments/20220413/594fb2e3/attachment.png>


More information about the users mailing list