Collatz_Sequences (3*N+1) in Console Example Demo for TCL V3

Collatz_Sequences (3*N+1) in Console Example Demo for TCL V3

This page is under development. Comments are welcome, but please load any comments in the comments section at the bottom of the page. Please include your wiki MONIKER and date in your comment with the same courtesy that I will give you. Aside from your courtesy, your wiki MONIKER and date as a signature and minimal good faith of any internet post are the rules of this TCL-WIKI. Its very hard to reply reasonably without some background of the correspondent on his WIKI bio page. Thanks, gold 20Aug2020



Preface


In 1937, Lothar Collatz conjectured that the Collatz Sequence of any positive number would begin repeating and coalesce to 1.


Introduction


Here are TCL calculations on the Collatz Sequences. The Collatz Sequences were named after German mathematician Lothar Collatz (1910–1990). Collatz conjectured that the Collatz Sequence of any positive number would begin repeating and coalesce to 1. The proc collatz_sequence was substantially rewritten by HE and replaced in the main deck with good valuable comments, which I will have to chew on. Primarily, I am interested in petitioning the code for Collatz_Sequences and modified_Collatz_Sequences to the TCLLIB. Many thanks to HE for comments and feedback.


The collatz_sequence proc returns the partial collatz_sequence from positive integers. This collatz_sequence proc can easily generate an endless loop. In fact, the known collatz_sequences are an endless list or repetitive string of integers. The iteration number is a stop or limit to iteration. By custom, the end of the partial collatz_sequence is 1 or start of repetition. For example, the collatz_sequence for integer 5 would be < 5 16 8 4 2 1 4 2 1 4 2 1 4 2 1 4 2 1 4 2 1 4 ...> The proc with entry 5 is intended to report the partial collatz_sequence of < 5 16 8 4 2 1 >. In the literature, the sequence < ... 16 8 4 2 1 ... > is called the tail on the known collatz_sequences. Many of the known collatz_sequences boil down to end and tail in < ... 16 8 4 2 1 ... > , so its somewhat counter intuitive to me that various positive integers have the same terminus in their collatz_sequence.


The logic order here for Collatz_Sequence is if odd, then N = ((3*$N+1)/3) and if even, then N = ( $N / 2 ). Others put logic as if $N even, return { $N / 2 } and If $N odd, return (3*$N+1). Continue the collatz_sequence until returned item is 1 or start of repetition. The speed of the supporting procs IsOdd and IsEeven were undetermined.


                # formula for Collatz_Sequence
                # By custom, the end of the partial collatz_sequence
                # is 1 or start of repetitive integers.
                # if odd, then N = ((3*$N+1)/2)
                # if even, then N = ( $N / 2 )
                if {$number % 2} {
                        # Odd ;
                        set number [expr {(3 * $number) + 1}]
                } else {
                        # Even ;
                        set number [expr {$number / 2}]
                }

Modified Collatz_Sequence


The modified_Collatz_Sequence is slightly different 2nd equation ((3*$N+1)/2), used for faster and different numbers resolution as outlined in [L1 ]. The formula for modified_Collatz_Sequence produces different terms, but resolves quicker in fewer terms. The logic is if odd, then N = ((3*$N+1)/2) and if even, then N = ( $N / 2 ). The modified formula in the following code may switched in the main _Collatz_Sequence proc.


Returning to the previous example, the collatz_sequence for integer 5 is < 5 16 8 4 2 1 > Whereas the modified_collatz_sequence for integer 5 is < 5 8 4 2 1 >. The modified_collatz_sequence offers fewer terms and faster resolution.


                # formula for modified_Collatz_Sequence
                # produces different terms, but resolves quicker in fewer terms
                # By custom, the end of the partial collatz_sequence
                # is 1 or start of repetitive integers.  
                # if odd, then N = ((3*$N+1)/2)
                # if even, then N = ( $N / 2 )
                if {$number % 2} {
                        # Odd ;
                        set number [expr {((3 * $number) + 1) / 2}]
                } else {
                        # Even ; 
                        set number [expr {$number / 2}]

Piece-wise Curve Fit to the Terminus of Collatz_Sequence


My back ground is engineering. When I am told to set a machine control system on the on the "safe part" of a complex curve, I will attempt a piece-wise curve fit on a complex curve. I look for parts of the curve that I know how to fit or understand. The start and middle of the Collatz_Sequence seems random looking, very unpredictable, and subject to initial conditions, meaning the starting integer which gives random looking results. In contrast and looking backwards from 1 at the end, the terminus of the known Collatz_Sequences is very familiar, known as the doubling equation of integer 2. The fit to the collatz_doubing equation as Y = A*EXP(B*X) Exponential.Returning to the previous example, the collatz_sequence for integer 5 is < 5 16 8 4 2 1 >. The exponential curve is matching 5/6 or 83.3 percent of the Collatz_Sequence for integer 5. Obviously, the fit will degrade with the longer Collatz_Sequence. But i think this is a start. Maybe the Collatz_Sequence is related to the doubling equation, exponentials, interest rate curves, and Gauss_Legendre correction constant. Refer to Gauss_Legendre correction constant using prime functions in TCLLIB primes::primesLowerThan [L2 ]. The accuracy of the Gauss_Legendre functions on prime number density is amazing to me, but I am not a pure mathematician.


Bottom Line. We now have exponential equation coefficients modeling the Collatz_Sequence tail as B or Beta constant 0.69314718055 (12 places) from double precision Fortran. Double precision Fortran at 12 places is roughly equivalent to TCL statement "set tclprecision 17" in the Collatz_Sequence test suite. Maybe this is overkill on precision. But the famous mathematicians Gauss and Legendre used rational numbers, exponential, and log equations to model the density of prime integer numbers on the number line. Legendre employed a corrective factor A of either 1 or approximately 1.08366 in his Gauss_Legendre formula, Prime integer number density P= N1 / (log (N1)-A). This is roughly equivalent to single precision in Fortran, although the mathematics of Gauss and Legendre predated the invention of the electronic computer and Fortran. Refer to Gauss_Legendre correction constant in the prime functions employed in TCLLIB primes::primesLowerThan [L3 ]. I agree that modeling parts of the Collatz_Sequences with exponentials and logs in rational numbers is a contrarian strategy and long shot. Frankly, my bets are on the rational number horses of Gauss and Legendre.


Terence Tao has published some auxiliary formulas for probability quantities etc from his Collatz_Sequences developments, which might be treated as large real precision numbers in TCL. Although Terence Tao does not use the TCL terms of real decimal numbers, as one might expect from the "pure". The Collatz_Sequence Orbit Expectation has the form expr { (1./2.)*log(3./4.)}, which approximates Negative -0.143 from the Tao paper. Generally, the Orbit Expectation E(P(N)) is negative or a reduction over the region < 0 ... N >. But the region < 0 ... (N+1) > might be different. The Gauss_Legendre formula, Prime integer number density P(N) = N1 / (log (N1)-A) is also over the region < 0 ... N >. Maybe comparing apples and oranges, the Gauss_Legendre formula is effectively a reduction of numbers to primes on the region < 0 ... N >. The Orbit Expectation E(P(N)) is effectively a reduction of the probability envelope striking individual N's over the region. As an example from a wildly different subject, the Gamblers Ruin Expectation E(P(N)) or Gamblers chance of going broke after N successive games is E(P(N)) = 0.5 + 0.25 + 0.125 + . . . until finish at formula E(P(N) = 1 - (1/2)^*N, which approaches 1. Check for 3 games is expr {0.5 + 0.25 + 0.125 } returns 0.875 and ''expr { 1. - (1./2.)**3. } returns 0.875. Check for 4 games is expr { 1. - (1./2.)**4. } returns 0.9375. The Gamblers Expectation of win over all games or original flush state at E(P(N)) = 0 is not expected here, but still can not be ruled out. Returning to "Orbit Expectation" and a little fuzzy on this conclusion, I think the Collatz_Sequence Orbit Expectation is E(P(N)) = expr { 1. -0.143} returns 0.857. The qualifiers in comparing other previous reports and different symbolic notation are tricky to me, but Allouche reported theta approx 0.869 and Korec reported theta approx 0.7924. Check that expr 4**(0.869**2) returns 2.848 and that expr 5**(0.869**2) returns 3.371.


Exponential curve fit to reverse_Collatz_Sequence , similar to doubling equation
1  1
2  2
3  4
4  8
5  16
Y = A*EXP(B*X)   Exponential curve fit, Levenberg_Marquadt fit to 12 places in double precision Fortran.
A =  0.50000000003E+00       SIGMAA =  0.15660160550E-10     0.319282E+11     0.000
B =  0.69314718055E+00       SIGMAB =  0.66408795386E-11     0.104376E+12     0.000
Res_av = 0.301611E-09 /   5   =>   Res_av = 0.603222E-10
       Chi-Square:
Deg. Freed.=  3  ChiSq.=0.300001E+01  Red. ChiSq.=0.100000E+01 => P(Red. ChiSq.)=0.391
       Correlation Coeficient:
R²yy(x) = 0.1000000E+01             adjR²yy(x) = 0.1000000E+01
Ryy(x) =  0.100000E+01  =>  P(NP,|R|) = 0.000E+00
B or Beta constant 0.69314718055 (12 places) is  expr { (exp (1))**0.69314718055 } evals 1.99999999998,  rounds to 2
found exact match on 5 of 6 points, expr { 5./6.  * 100. } # returns 83.33 percent 

Body : Comments and Rewrite by HE


HE 2021-09-11: Hello Gold, I have a bunch of suggestions/questions about the code. Mainly in respect to other operating systems but, also if one is using your code in a win10 or related system. This is not to bother you.


As far as I understand your code is planned to be executed on a command line. There is no input. And, output is completely done by using 'puts'. It also use only commands/procedures provided by a Tcl only installation (beside some lines I will discuss below). That means the code should be possible to execute everywhere where we can call a tclsh and copy or source the code into it.


Poorly this doesn't work. Because the code contains "package require Tk" without using any GUI and some installation will not have a Tk. And using the command 'console' which is only available in wish.exe but not in wish compiled for Linux, for example.


For sure some could simply copy the code between "package require Tk" and the usage of 'console' at the end to try to get it running. That will not work because there is a 'console show' in between. This needs also to be excluded. At the end the user interested of the result of your script needs to investigate the code to get it running. A bit inconvenience from my point of view. Particularly because all the problematic lines are mainly for eye candy only.


How would I try to execute this type of scripts: On win10 I would open a wish. It displays a console window. I would make a copy and past (c&p) of the code into this console window. The output would be crude to read because of:

  • all the output before "proc table_format_out ..." would not be easy to read because the 'puts' lines and the output are interchanging.
  • The change of font and geometry left a console window far to big on some displays and not able to show the text in a readable way. At least not for me.
  • I don't discuss the format of the able output here, because this also not help to read the results.

Next try would be to open a tclsh on win10 and c&p the code into it. The result is similar. The font size and console background can't be changed so it is more comfortable to read. But the other issues mentioned above still exists and in addition we have the error message in between about the 'console' command.


Next try would be to store it in a file, start a tclsh on win10 (because "package require Tk" let me think it is planned to do so) and source the file into it. This simply raise a "Invalid command name "console"". This will be the same on Linux.


Next try would be to start a wish on win10 and source the stored file into it. I think that is the result you wanted. But, eye candy for you on your computer doesn't fit well on my computer. You also don't know if the user will have problems with a green background. And a smaller font size would show more from the table. At least on the computer I tried your code.


Now I tried all four variants on Linux. Sourcing the file lead in both cases to error message "invalid command name "console"" without any other output. C&p into a wish or tclsh lead to the ugly output where it is not clear where to look for the wanted result.


What I would change:

  • To be platform independent I would remove "package require Tk" and the 'console' lines.
  • To be able to run it by double-click inside win10 I would add somewhere at the top of the script:

if {$tcl_platform(platform) == {windows}} {
        console show
}

  • I would put all output into one procedure so that the last command could this procedure and afterwards all output is generated.

Sorry again, for all the comments only because of output and executing. I tend to write to much in case I try to explain my view. But look how easy it is to make the code run in 8 different conditions instead only running under one condition.


Until here, I read so often this piece of code that I found some small other items:

  • Procedures isPositive and isNegative are not used. Perhaps, isPositive was planned to be used in collatz_sequence as a protection not to use negative numbers?
  • "set tclprecision 17" is used. The Tcl 8.6 documentation tells "It defaults to 0. Applications should not change this value;". I'm not sure to understand why it is used. The whole math of that problem should be integer calculation. At least until the limit of 8 byte integer is crossed. And as long as no fraction is forced the math should stay integer. Perhaps, I'm wrong. But, that is I understood how Tcl calculation works.
  • Where you are using the math packages you load in the beginning? I can't find the usage of it. I would understand "package require math::bignum" to be able to calculate behind the 8 byte integer limit. But the named one?

HE 2021-09-12: Since my comment yesterday, all comment lines are changed from '#' to ';#' at the beginning. Is there a reason for this? From my knowledge a ';' is not need for a proper comment at the beginning of a line. Only if the comment is behind a command on the same line a ';' is needed before the '#' to separate both commands.


HE 2021-09-12: As an answer of your question on Ask, and it shall be given # 13 here my version of collatz_sequence based on your one.

  • For loop provide everything to control iteration.
  • Some tests in the beginning to assure that positive integers are used for number and iteration.

That makes it easier to stop as we find 1 as a result. At least the first 10 million integer I tried to use for number will all end with 1 and then go to the endless sequence. As far as I understood others are tried far higher numbers with the same end. Also I would not check separately for odd and even. One check is enough. And I used the expression itself instead of put it into a separate procedure. This will spare calculation power with bigger numbers.


Easy Eye Concept for Windows10 Console


The easy eye calculator includes large black font on green background. The human eye is peaked for yellow/green and various ergonomic studies have shown that black font on green background is one of the easiest to read. The easy eye concept is similar to the more legible screens in the older monochrome green screens and monochrome yellow screens, as well as the old MS-DOS texteditor program Wordstar. Used in military green screens, also. My small notepad has a linked script and icon for easy eye calculator, posted on the windows desktop of small screen, 22 by 12 cm. One advantage of the easy eye calculator is that the calculations are posted to a console window as a sort of paper tape. The easy eye calculations can be cut and paste, saved to a word processor. The easy eye calculator is a compilation of several eval calculators on the TCL wiki.


gold However, HE suggestion for Windows10 Console programs allowing user preference for screen background and choose fonts is good. One can change the color and fonts right now through the top boxes on the Windows10 console. Probably one would need to access a storage file for preferences. Have to think on this. Not everybody has my bad eyes, so tired from 50 years of tiny computer fonts.



Test Suite


The test suite for Collatz_Sequences has been completed and forwarded attached to ticket e035b93f36. However, the Collatz_Sequences test suite has many dependencies on the Windows10 PC and the ( ActiveState ) TCL Comsole window. At present, all i do is tap once on the icon on the Windows PC; the icon text is linked to ActiceState TCL. And I am up and running on test suite gui for Collatz_Sequences. I am not sure how one could test a numeric program without some listing of canned test cases, printout, or other wiki style printout? I might point that to test compatibility with TCLLIB, I do test homebrew code loaded in the local copy of TCLLIB math and associated libraries. This is a local setup on Windows10 PC and ActiceState TCL libraries, so references to a my local TCLLIB::math library and the ( ActiveState ) TCL Comsole window might not be easily portable, based on UNIX comments received here. I suppose that the Collatz_Sequences test suite could be compiled to a Windows10 executable, but then the testing and issues on UNIX machines still remain unclear at present.


Pushbutton Operation


Alternate Draft text from test suite. 1) initial integer N1 2) iteration limit $iteration 3) optional index for heads and tails, usually 4 4) optional mode constant 1 or 2, calc reverts to number of calc steps This calculator returns the partial Collatz_Sequence based on initial integer and iteration number of steps optional constant mode, usually 1 for no decay, not used & open yet, optional constant iteration is safety break for brevity and counter endless loops iteration maybe cut short for brevity The collatz_sequence proc returns the partial collatz_sequence from positive integers. This collatz_sequence proc can easily generate an endless loop. In fact, the known collatz_sequences are an endless list or coalesce to 1 or a repetitive string of integers. The iteration number is a stop or limit steps of iteration. By custom, the end of the partial collatz_sequence is 1 or start of repetition integers max_values_list is short list of maximum values in list, number of maximum values controlled by an index number collatz_sequence_head is initial values at start of sequence collatz_sequence_tail is initial values at end of sequence optional mode constant 1 or 2, calc reverts to number of calc steps: mode_option 1 is collatz_sequence mode_option 2 is modified_collatz_sequence if mode 2 used, best to clear and recycle with another testcase collatz_sequence_length is maximum length of partial collatz sequences warning!!! if index & iteration activated for brevity, sequence list maybe cut short collatz_sequence is list of collatz_sequence warning!!! if index & iteration activated for brevity, sequence list maybe cut short steps_iteration_total is total number of steps used in calc proc For comparison, TCL code may include redundant paths & formulas. The TCL calculator normally uses modern units for convenience to modern users and textbooks. Any convenient and consistent in/output units might be used like inches, feet, nindas, cubits, or dollars to donuts. Recommended procedure is push testcase and fill frame, change first three entries etc, push solve, and then push report. Report allows copy and paste from console to conventional texteditor. For testcases testcase number is internal to the calculator and will not be printed until the report button is pushed for the current result numbers. Use one line errorx proc to estimate percent errors. errorx proc is used in the report window (console). Additional significant figures are used to check the TCL program, not to infer the accuracy of inputs and product reports. index is number of sequence values displayed from start of sequence warning!!! if index & iteration activated for brevity, sequence list maybe cut short, including integers, maximum values, heads and tails reported comments are placed outside these working routines because comments are deleted in final TCLLIB version, I think.


For the push buttons on the TCL calculator, the recommended procedure is push testcase and fill frame, change first three entries etc, push solve, and then push report. Report allows copy and paste from console. For testcases in a computer session, the TCL calculator increments a new testcase number internally, eg. TC(1), TC(2) , TC(3) , TC(N). The testcase number is internal to the calculator and will not be printed until the report button is pushed for the current result numbers. The current result numbers will be cleared either on the next clear button or on the next solve button.



Conclusions


gold Many thanks to HE for comments and feedback. In terms of use on other TCL platforms, I am interested in proving and petitioning the collatz_sequence code to the TCLLIB. On my own PC on Windows 10, mostly I attach a proven subroutine to the command line interface and type into the TCL Windows10 console, meaning Easy Eye [L4 ]. At present, all i do is tap once on the icon (text linked to ActiceTCL) of the Easy Eye console and I am up and running. I am not sure how one could test a numeric program without some listing of canned test cases, printout, or other wiki style printout? I might point that to test compatibility with TCLLIB, I do test homebrew code loaded in the local copy of TCLLIB math and associated libraries.This is a local setup on Windows10, so references to a my local TCLLIB::math library would not be portable.


gold 2021-09-13. "And slowly, I turn inch by inch" - Movies. I have swapped ;# for # in comment lines. I have seen punctuation ;# semicolon hash and set list_values { 1 2 3 4 } before as a list creation, meaning from some professional coders on the internet. But I will defer to your judgement here. In 2020, starting values up to 2**268 approximating 2.95*1020 have been checked in the Collatz conjecture. Yes, one would need math::bignum package for that and to check all speed savings on supporting integer procs for Collatz sequences at that size. Recognize that collatz_sequence are considered integer sequences, but Gauss and Legendre used exponential and logs on real numbers to predict the Prime integer number density on the numberline. Terence Tao has published some auxiliary formulas for probability quantities etc from his Collatz_Sequences developments, which might be treated as large real precision numbers in TCL. Although Terence Tao does not use the TCL terms of real decimal numbers, as one might expect from the "pure". I am loading my exponential cannon with real numbers and TCL gunpowder, set tclprecision 17. Refer to Gauss Approximate Number of Primes and eTCL demo example calculator.


gold 2021-09-13. Solved problem. The proc collatz_sequence was substantially rewritten by HE and I replaced in the main deck and good feedback comments, which I will have to chew on. Many thanks to HE. I checked the proc collatz_sequence in small test suite and proc looks good, so I will pass ticket on to TCLLIB math. I have loaded the ticket e035b93f36 Title: Collatz_Sequence, modified_Collatz_Sequence, positive & negative logic test for integers.


gold 2021-09-13. These calculator approaches in TCL console guis for Windows10 may seem trivial math to some, but I have submitted 4 or 5 TCLLIB tickets to improve the TCLLIB math library. For example, the math and logic functions IsOdd, IsEven, IsNegative, IsPositive, figurative_numbers, and Quadratic_Equation_Solution_for_reals were not in the TCLLIB library, as near as I can tell. Maybe these logic functions on integers and Quadratic_Equations_Solutions on reals are trivial math to some, but these Quadratic_Equations_Solutions and other math functions show up in some other math languages, TCL programs, and even TCL WIKI pages. As HE implies, the main idea of TCL or other computer language is that other users can share the faster compiled code rather than homebrew functions. Since I am retired and I do not have easy access to a UNIX machine, the only course in the retirement economy is to proof the TCL routines on a Windows10 PC.



References:


  • Wikipedia search engine < Collatz Sequences >
  • Wikipedia search engine < Lothar Collatz Sequences >
  • Wikipedia search engine < Programming Examples >
  • Google search engine < vaporware >
  • Google search engine < Collatz_Sequences >
  • Book >> How to Prove The Collatz Conjecture Paperback, 2005, by Danny Fleming
  • Ultimate Challenge: the 3x + 1 problem: edited by Jeffrey Lagarias,
  • One Liners Programs Pie in the Sky
  • One Liners
  • One Liners Programs Compendium [L5 ]
  • WIKI BOOKS, Programming_Examples pdf
  • WIKI BOOKS, Tcl_Programming_Introduction pdf
  • google search engine < Collatz Conjecture >
  • switch
  • Tcl Tutorial Lesson 6
  • Math Sugar Richard Suchenwirth RS
  • Practical_Advice_on_Quotes_and_Brackets_in_TCL
  • tmml.sourceforge.net/doc/tcllib [L6 ]
  • rosettacode.org/wiki/Even_or_odd [L7 ]
  • en.wikipedia.org/wiki/Collatz_conjecture
  • Tao, Terence , 2019. "Almost all Collatz orbits attain almost bounded values".
  • Project Euler 14: Longest Collatz sequence, Peter Prevos
  • Mathematician Proves Huge Result on ‘Dangerous’ refer to Terence Tao
  • Terence Tao realized that the Collatz conjecture was similar to partial differential equations.
  • The Tao starting sample weighs toward numbers that
  • have a remainder of 1 after being divided by 3,
  • and away from numbers that have a remainder of 2 after being divided by 3.
  • TCL pseudocode
  • remove all numbers divisible by 3 on a list of integers,
  • find all numbers that have a remainder of 1, when divided by 3.
  • see modified Collatz formula in en.wikipedia.org/wiki/Collatz_conjecture
  • Barina, David (2020). "Convergence verification of the Collatz problem". The Journal of Supercomputing.
  • Random Walk Equation Slot Calculator Example
  • oeis.org/A070165, abbreviation for "The On-Line Encyclopedia of Integer Sequences"
  • docs.google.com/spreadsheets/d/1TB5FpgjsYVAyuqQKu4WDrmB5u7UDUY5KaQZfjqPNr9I/edit#gid=0
  • Collatz Conjecture: Spreadsheet 2021,
  • Project: Spreadsheet Based Modelling for Education and Research
  • Amro Mohamed Elfeki, Mansoura University
  • rosettacode.org/wiki/Rosetta_Code
  • rosettacode.org/wiki/Hailstone_sequence, not sure of permissions and usage
  • But I suppose these Rosetta_code functions would be useful in Collatz Sequences, proposed library in TCLLIB.
  • (Awaiting Moderator Approval) Add Collatz_Sequences and modified Collatz_Sequences to ticket e035b93f36
  • Ticket completed. Gauss / Legendre functions for number of primes in TCLLIB
  • Ticket completed, Request for math::number_theory.
  • would be handy to have 3 prime number functions like approx_number_primes = N1 / ln (N1),
  • legendre_primes2 = N1 / (ln (N1)-1),modified_legendre_primes3 = N1 / (ln (N1)-1.08366).
  • (Awaiting Moderator Approval) New ticket 5af6381a8b Quadratic Equation Solution, 2 reals from Muller's method.
  • New ticket f8adb7a036 figurate numbers and sums of powers.
  • Ticket completed, prime gap function and sets of twin primes,cousin primes,twin primes

proposed Collatz_Sequences and modified Collatz_Sequences functions in TCLLIB.


collatz_sequence_head (27, 4 ) evals  27 82 41 124
collatz_sequence_head (27, 3 ) evals  27 82 41  
collatz_sequence_head (27, 2 ) evals  27 82  
collatz_sequence_head (27, 1 ) evals  27    , initial entry 
collatz_sequence_head (10, 3 ) evals  5 16 8 
collatz_sequence_tail (27, 4 ) evals 8 4 2 1
collatz_sequence_tail (27, 3 ) evals 4 2 1
collatz_sequence_tail (27, 2 ) evals  2 1
collatz_sequence_tail (27 , 1 ) evals   1, final entry
collatz_sequence_tail (10 , 3 ) evals  4 2 1   
collatz_sequence_tail (27, 4 ) evals 8 4 2 1
collatz_sequence_max_sequence_value (27)  evals  9232?
collatz_sequence_max_sequence_value (10)  evals  6
collatz_sequence_length (10)  evals 6
collatz_sequence_length (27)  evals 111?
collatz_sequence_generate  (5) evals  5 16 8 4 2 1 
collatz_sequence_generate  (27) evals 27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
reverse_collatz_sequence_generate (5) 1 2 4 8 16 5
reverse_collatz_sequence_generate (7) 1 2 4 8 16 5 10 20 40 13 26 52 17 34 11 22 7
reverse_collatz_sequence_generate (10) 1 2 4 8 16 5 10 
reverse_collatz_sequence_generate (27) 1 2 4 8 16 5 10 20 40 80 160 53 106 35 70 23 46 92 184 61 122 244 488 976 325 650 1300 433 866 1732 577 1154 2308 4616 9232 3077 6154 2051 4102 1367 2734 911 1822 3644 7288 2429 4858 1619 3238 1079 2158 719 1438 479 958 319 638 1276 425 850 283 566 1132 377 754 251 502 167 334 668 1336 445 890 1780 593 1186 395 790 263 526 175 350 700 233 466 155 310 103 206 412 137 274 91 182 364 121 242 484 161 322 107 214 71 142 47 94 31 62 124 41 82 27
# using index number in second position
# Many known collatz_sequences coalesce to 1 to similiar tail, 16 8 4 2 1 
# so may have to  index to 8 or 9 to show any differences in reverse_collatz_sequence(N)
reverse_collatz_sequence_head (10 3) 1 2 4 
reverse_collatz_sequence_head (5 4) 1 2 4 8 
# reporting number of computation steps for collatz_sequence(N) , would also be useful
collatz_sequence_steps (27) returns 112?
collatz_sequence_steps (10) returns 6?
collatz_sequence_steps (50) returns 21?
# collatz_sequence sorted from maximum to minimum value
collatz_sequence_maximum_values (5)  returns 16 8 5 4 2 1
collatz_sequence_maximum_values_short_list (10 3) returns 16 8 10?


Screenshots Section


figure 1a. Screenshot, Collatz_Sequences_(3*N+1) _screenshot


Collatz_Sequences_(3*N+1) _screenshot



figure 1b. Screenshot, Collatz_Sequences_screenshot_gui


Collatz_Sequences_screenshot_gui


figure 2. Collatz_Sequences_double_collatz


Collatz_Sequences_double_collatz


figure 3. [Collatz_Sequences_residuals


Collatz_Sequences_residuals


Testcases Section


In planning any software, it is advisable to gather a number of testcases to check the results of the program. ---

Testcase 1, Partial Collatz_Sequences



table, Partial Collatz_Sequences printed inTCL format
number iteration partial Collatz_Sequences comment, if any
3 5 3 10 5 16 8 4 2 1
4 5 4 2 1
5 5 5 16 8 4 2 1
6 5 6 3 10 5 16 8 4 2
7 5 7 22 11 34 17 52 26 13 40
8 5 8 4 2 1
9 5 9 28 14 7 22 11 34 17 52
10 5 10 5 16 8 4 2 1
11 5 11 34 17 52 26 13 40 20
12 5 12 6 3 10 5 16 8 4
13 5 13 40 20 10 5 16 8
14 5 14 7 22 11 34 17 52 26 13 40
15 5 15 46 23 70 35 106 53 160 80
16 5 16 8 4 2 1
17 5 17 52 26 13 40 20 10
18 5 18 9 28 14 7 22 11 34 17 52
19 5 19 58 29 88 44 22 11 34
20 5 20 10 5 16 8 4 2


Testcase 2, Collatz_Sequence for integer 7 from Windows10 gui


table 2, Collatz_Sequence for integer 7 from Windows10 gui printed in tcl wiki format
quantity value value comment, if any
1:testcase_number
7.0 :initial integer
20.0 :iteration limit , safety maybe cut short :
4.0 :optional index_tails for heads, max values, and tails, usually 4 :
17 :number of calculation steps or optional constant , nominal 1 :
17 : steps_iteration_total:
52 34 26 : collatz_sequence short list of maximum values :
7 22 11 34 17 : collatz_sequence_head :
16 8 4 2 1 : collatz_sequence_tail :
17 : collatz_sequence_length:
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 : Collatz_Sequence values :
Collatz_Sequence : 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1


Testcase , Partial Collatz_Sequence for integer 7 from Windows10 gui


table 4, modified_Collatz_Sequence for integer 27 from Windows10 gui printed in tcl wiki format
quantity value value comment, if any
4:testcase_number
27.0 :initial integer
100.0 :iteration limit , safety maybe cut short :
4.0 :optional index_tails for heads, max values, and tails, usually 4 :
71 :optional constant , nominal 1, calc reverts to number of calc steps :
71 : steps_iteration_total:
4616 : collatz_sequence short list of maximum values :
27 41 62 31 : collatz_sequence_head :
8 4 2 1 : collatz_sequence_tail :
71 : collatz_sequence_length:
Collatz_Sequence : 27 41 62 31 47 71 107 161 242 121 182 91 137 206 103 155 233 350 175 263 395 593 890 445 668 334 167 251 377 566 283 425 638 319 479 719 1079 1619 2429 3644 1822 911 1367 2051 3077 4616 2308 1154 577 866 433 650 325 488 244 122 61 92 46 23 35 53 80 40 20 10 5 8 4 2 1


Testcase , Collatz_Sequence for integer 10 from Windows10 gui


table 2, Collatz_Sequence for integer 7 from Windows10 gui printed in tcl wiki format
quantity value value comment, if any
2:testcase_number
10.0 :initial integer
100.0 :iteration limit , safety maybe cut short :
4.0 :optional index_tails for heads, max values, and tails, usually 4 :
6 :optional constant , nominal 1, calc reverts to number of calc steps :
6 : steps_iteration_total:
10 : collatz_sequence short list of maximum values :
10 5 8 4 : collatz_sequence_head :
8 4 2 1 : collatz_sequence_tail :
6 : collatz_sequence_length:
10 5 8 4 2 1 : Collatz_Sequence values :
Collatz_Sequence : 10 5 8 4 2 1


Testcase , Collatz_Sequence for integer 7 from Windows10 gui


table 3, Collatz_Sequence for integer 7 from Windows10 gui printed in tcl wiki format
quantity value value comment, if any
3:testcase_number
7.0 :initial integer
100.0 :iteration limit , safety maybe cut short :
4.0 :optional index_tails for heads, max values, and tails, usually 4 :
12 :optional constant , nominal 1, calc reverts to number of calc steps :
12 : steps_iteration_total:
26 : collatz_sequence short list of maximum values :
7 11 17 26 : collatz_sequence_head :
8 4 2 1 : collatz_sequence_tail :
12 : collatz_sequence_length:
7 11 17 26 13 20 10 5 8 4 2 1 : Collatz_Sequence values :
Collatz_Sequence : 7 11 17 26 13 20 10 5 8 4 2 1


Testcase , modified__Sequence for integer 10 from Windows10 gui


table 2 modified_Collatz_Sequence printed in tcl wiki format
quantity value value comment, if any
2:testcase_number
10.0 :initial integer
100.0 :iteration limit , safety maybe cut short :
4.0 :optional index_tails for heads, max values, and tails, usually 4 :
6 :optional constant , nominal 1, calc reverts to number of calc steps :
6 : steps_iteration_total:
10 : collatz_sequence short list of maximum values :
10 5 8 4 : collatz_sequence_head :
8 4 2 1 : collatz_sequence_tail :
6 : collatz_sequence_length:
10 5 8 4 2 1 : Collatz_Sequence values :
Collatz_Sequence : 10 5 8 4 2 1


Testcase , modified__Collatz_Sequence for integer 10 from Windows10 gui


table 4, modified__Sequence for integer 10 printed in tcl wiki format
4:
10.0 :initial integer
20.0 :iteration limit , safety maybe cut short :
4.0 :optional index_tails for heads, max values, and tails, usually 4 :
7 :optional constant , nominal 1, calc reverts to number of calc steps :
7 : steps_iteration_total:
16 : collatz_sequence short list of maximum values :
10 5 16 8 : collatz_sequence_head :
8 4 2 1 : collatz_sequence_tail :
7 : collatz_sequence_length:
10 5 16 8 4 2 1 : Collatz_Sequence values :
Collatz_Sequence : 10 5 16 8 4 2 1


Testcase , Partial Collatz_Sequence for integer 7 from Windows10 gui


table 3, Regular Collatz_Sequences (3*N+1) for integer 7 from Windows10 gui printed in tcl wiki format
quantity value value comment, if any
3:testcase_number
27.0 :initial integer
120.0 :iteration limit , safety maybe cut short :
4.0 :optional index_tails for heads, max values, and tails, usually 4 :
112 :optional constant , nominal 1, calc reverts to number of calc steps :
112 : steps_iteration_total:
9232 : collatz_sequence short list of maximum values :
27 82 41 124 : collatz_sequence_head :
8 4 2 1 : collatz_sequence_tail :
112 : collatz_sequence_length:
Collatz_Sequence : 27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1

Appendix TCL programs and scripts


Pretty Print Version


Main Deck

        proc collatz_sequence {number iteration} {
        # Check parameter
        if {!([string is wideinteger $number] && $number > 0)} {
                error "Number '$number' is not positiv integer!"
        }
        if {!([string is wideinteger $iteration] && $iteration > 0)} {
                error "Iteration '$iteration' is not positiv integer!"
        }
        # Initialisation
        set sequence [list $number]

        # Interations
        for {set n 0} {$n <= $iteration} {incr n} {
                if {$number == 1} {
                        return $sequence
                }
                if {$number % 2} {
                        # Odd
                        set number [expr {(3 * $number) + 1}]
                } else {
                        set number [expr {$number / 2}]
                }
                lappend sequence $number
        }
        # After value reach 1 it is a endless sequence of 4 2 1 4 2 1 ...
        # If we reach not 1 during the given ammount of iteration
        # we raise an error to signal that number of iterations are to small
        # or we reach the case all looking for.
        error "Number of iteration '$iteration' reached without getting 1!"
        }



Pseudocode and Equations Section

     #pseudocode can be developed from rules of thumb.
     #pseudocode: some problems can be solved by proportions (rule of three), to some order of magnitude
     #pseudocode: enter quantity1,  quantity2, quantity3 and expected output (quantity4) for testcases.
     #pseudocode: enter time in years, number of remaining items
     #pseudocode: output fraction of (remaining items) over (items at time zero)
     #pseudocode: ouput remaining items as fraction or percent
     #pseudocode: output fraction of (quantity4 ) over ( quantity1 at time zero)
     #pseudocode: output fraction of (quantity2) * (quantity3 ) over (quantity1 at time zero)
     #pseudocode: outputs should be in compatible units.
     #pseudocode: rules of thumb can be 3 to 15 percent off, partly since g..in g..out.
     #pseudocode: need test cases > small,medium, giant
     #pseudocode: need testcases within range of expected operation.
     #pseudocode: are there any cases too small or large to be solved?
     ; Terence Tao realized that the Collatz conjecture was similar to partial differential equations.
     ;  The Tao starting sample weighs  toward numbers that
     ; have a remainder of 1 after being divided by 3,
     ; and away from numbers that have a remainder of 2 after being divided by 3.
     ;  TCL pseudocode
     ;  remove all numbers divisible by 3 on a list of integers, 
     ;  find all numbers that have a remainder of 1, when divided by 3.




Hidden Comments Section

Please include your wiki MONIKER and date in your comment with the same courtesy that I will give you. Thanks, gold 12Aug2020

HE 2021-09-11: Hello Gold, I have a bunch of suggestions/questions about the code. Mainly in respect to other operating systems but, also if one is using your code in a win10 or related system. This is not to bother you.

As far as I understand your code is planned to be executed on a command line. There is no input. And, output is completely done by using 'puts'. It also use only commands/procedures provided by a Tcl only installation (beside some lines I will discuss below). That means the code should be possible to execute everywhere where we can call a tclsh and copy or source the code into it.

Poorly this doesn't work. Because the code contains "package require Tk" without using any GUI and some installation will not have a Tk. And using the command 'console' which is only available in wish.exe but not in wish compiled for Linux, for example.

For sure some could simply copy the code between "package require Tk" and the usage of 'console' at the end to try to get it running. That will not work because there is a 'console show' in between. This needs also to be excluded. At the end the user interested of the result of your script needs to investigate the code to get it running. A bit inconvenience from my point of view. Particularly because all the problematic lines are mainly for eye candy only.

How would I try to execute this type of scripts: On win10 I would open a wish. It displays a console window. I would make a copy and past (c&p) of the code into this console window. The output would be crude to read because of:

  • all the output before "proc table_format_out ..." would not be easy to read because the 'puts' lines and the output are interchanging.
  • The change of font and geometry left a console window far to big on some displays and not able to show the text in a readable way. At least not for me.
  • I don't discuss the format of the able output here, because this also not help to read the results.

Next try would be to open a tclsh on win10 and c&p the code into it. The result is similar. The font size and console background can't be changed so it is more comfortable to read. But the other issues mentioned above still exists and in addition we have the error message in between about the 'console' command.

Next try would be to store it in a file, start a tclsh on win10 (because "package require Tk" let me think it is planned to do so) and source the file into it. This simply raise a "Invalid command name "console"". This will be the same on Linux.

Next try would be to start a wish on win10 and source the stored file into it. I think that is the result you wanted. But, eye candy for you on your computer doesn't fit well on my computer. You also don't know if the user will have problems with a green background. And a smaller font size would show more from the table. At least on the computer I tried your code.

Now I tried all four variants on Linux. Sourcing the file lead in both cases to error message "invalid command name "console"" without any other output. C&p into a wish or tclsh lead to the ugly output where it is not clear where to look for the wanted result.

What I would change:

  • To be platform independent I would remove "package require Tk" and the 'console' lines.
  • To be able to run it by double-click inside win10 I would add somewhere at the top of the script:
if {$tcl_platform(platform) == {windows}} {
        console show
}
  • I would put all output into one procedure so that the last command could this procedure and afterwards all output is generated.

Sorry again, for all the comments only because of output and executing. I tend to write to much in case I try to explain my view. But look how easy it is to make the code run in 8 different conditions instead only running under one condition.

Until here, I read so often this piece of code that I found some small other items:

  • Procedures isPositive and isNegative are not used. Perhaps, isPositive was planned to be used in collatz_sequence as a protection not to use negative numbers?
  • "set tclprecision 17" is used. The Tcl 8.6 documentation tells "It defaults to 0. Applications should not change this value;". I'm not sure to understand why it is used. The whole math of that problem should be integer calculation. At least until the limit of 8 byte integer is crossed. And as long as no fraction is forced the math should stay integer. Perhaps, I'm wrong. But, that is I understood how Tcl calculation works.
  • Where you are using the math packages you load in the beginning? I can't find the usage of it. I would understand "package require math::bignum" to be able to calculate behind the 8 byte integer limit. But the named one?

HE 2021-09-12: Since my comment yesterday, all comment lines are changed from '#' to ';#' at the beginning. Is there a reason for this? From my knowledge a ';' is not need for a proper comment at the beginning of a line. Only if the comment is behind a command on the same line a ';' is needed before the '#' to separate both commands.

HE 2021-09-12: As an answer of your question on Ask, and it shall be given # 13 here my version of collatz_sequence based on your one. For loop provide everything to control iteration. Some tests in the beginning to assure that positive integers are used for number and iteration. That makes it easier to stop as we find 1 as a result. At least the first 10 million integer I tried to use for number will all end with 1 and then go to the endless sequence. As far as I understood others are tried far higher numbers with the same end. Also I would not check separately for odd and even. One check is enough. And I used the expression itself instead of put it into a separate procedure. This will spare calculation power with bigger numbers.


Main Deck

        proc collatz_sequence {number iteration} {
        # Check parameter
        if {!([string is wideinteger $number] && $number > 0)} {
                error "Number '$number' is not positiv integer!"
        }
        if {!([string is wideinteger $iteration] && $iteration > 0)} {
                error "Iteration '$iteration' is not positiv integer!"
        }
        # Initialisation
        set sequence [list $number]

        # Interations
        for {set n 0} {$n <= $iteration} {incr n} {
                if {$number == 1} {
                        return $sequence
                }
                if {$number % 2} {
                        # Odd
                        set number [expr {(3 * $number) + 1}]
                } else {
                        set number [expr {$number / 2}]
                }
                lappend sequence $number
        }
        # After value reach 1 it is a endless sequence of 4 2 1 4 2 1 ...
        # If we reach not 1 during the given ammount of iteration
        # we raise an error to signal that number of iterations are to small
        # or we reach the case all looking for.
        error "Number of iteration '$iteration' reached without getting 1!"
        }

Hidden Comments Section

Please include your wiki MONIKER and date in your comment with the same courtesy that I will give you. Thanks, gold 12Sep2021 Works with: Tcl version 8.5 Use the {*} expansion operator to substitute the list value with its constituent elements

package require Tcl 8.5

set values {4 3 2 7 8 9} ::tcl::mathfunc::max {*}$values ;# ==> 9


  Hidden Comments Section


  test for hidden comments stop

test! seems to work


  Hidden Change Log Section

gold 9/11/2021. first edit XXXxxx


gold 9/12/2021. replaced original proc with HE proc, dropped extraneous procs isPositive, isNegative, isOdd, and isEven as confusing to readers. Procs still on ticket if feasible for TCLLIB. In 2020, starting integer values up to 2**268 approximating 2.95*1020 and associated sequences have been checked in the Collatz conjecture. Yes, one would need math::bignum package for that and to check all speed savings on supporting integer procs for Collatz sequences at that size. x


gold 9/13/2021. added modified_collatz_sequence formulas, replaced :# with #.


gold 9/13/2021. forwarded ticket on collatz_sequences to TCLLIB. I have loaded the ticket e035b93f363dc62153375b77ad3bcf339a68d407 Title: Collatz_Sequence, modified_Collatz_Sequence, posiitve & negative logic test for integers.