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 02JAN2024
gold Hi, I'm an old Fortran programmer trying to retread. I actually served time on the IBM punch card machines. I collect old Fortran77 books as a hobby. A lot of guys leaving work would give me their old Fortran77 books. On active, i had a large Fortran collection, almost a library. I would loan and check out Fortran77 books to other employees. Also I programmed a lot in Javascript. Mostly I work on TCL now because i am visually oriented and think that a gui can save a lot of time in engineering calculations.
gold6/2/2021. How did you discover TCL/TK ???? >>
gold About 1996, the Personal Computer PC on my desk, was replaced by a Sun Sparc 20 workstation. I was an engineer and mainly programming in Fortran 77. I had learned QuickBasic, Html, Perl (Unix), and also Javascript. Since the Sparc 20 interface was command line Unix, I looked around for a gui or gui language as an interface to the Sparc 20 workstation. I found Tool Control Language TCL fairly easy to mouse click and invoke executable icons on the Xwindows screen. I even had a gimpy trashcan icon on the screen. I showed my beginner TCL program to a co_worker and he said I had fairly imitated the the PC Windows icon system on a Sparc20 workstation. But this was only about 200 lines of beginner TCL code and fast as greased lightning on a Sparc20! How's that for a sales job on TCL? Then, I wrote small slot calculators in TCL and Javascript on the Sparc20 behind a firewall, which were similar to my later pages on this wiki. Never forget the human brain evolved to hunt rabbits, not Unix critters and command lines. Your eyes and brain modeling/mapping of the outside stims are closer to a gui screen than one might think.
This page on developing pseudocode examples and one line procedures is not a replacement for the current Tcl core and Tcllib, which is much improved since Tcl version 4, and other <faster> language constructs. math ops, Tcllib routines, and other compiled routines can reduce the cost of big-data tasks by about 1/3. The time savings of the core are not always obvious on small quantities of data, like 4 or 5 numbers. Performance of one-line programs may suffer degradation due to lengthy recursion calls, and may be limited by constraints on recursion. Dependence on math operator notation, helper procedures, math check examples, degradation due to lengthy recursion calls, and special library functions should be noted in the comment lines.
gold 2021-09-13. These small TCL graphical user interface guis presented in the wiki for Windows10 may seem trivial math to some, but I have submitted 4 or 5 TCLLIB tickets to improve the TCLLIB math library. Many thanks to arjen & Andreas Kupries for the heavy lifting. For example, the math and logic functions IsOdd, IsEven, IsNegative, IsPositive, figurative_numbers, twin_primes, and Quadratic_Equation_Solution_for_reals were not in the TCLLIB library, as near as I can tell. Maybe these logic functions on integers, Quadratic_Equations on reals, Collatz functions, and Quantum math calculations are trivial math to some, but these math functions and quadratic equations show up in some other math languages, offsite TCL programs, and even TCL WIKI pages. As discussion with 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. I am retired and since I do not have easy access to a UNIX machine anymore, the only course is to proof the TCL routines on a Windows10 PC with ActiveState TCL.
gold Thanks for feedback. These pages is a learning experience (for me). These pade_trig functions in script are very slow and inaccurate past pi/4, compared to the hardware solutions. I will leave the pade_trig procs and Sagemath script (Taylor/Pade/Horner generators) in the alternate listings for the curious reader. If saving computation time, the Sagemath script should be able to convert the odd polynomial into Horner form. I don't see many procs of Pade quotient functions in TCL language on this wiki, so maybe something has been gained.
Npte: Some tickets are closed and functions available in Tcllib. Many thanks to arjen & Andreas Kupries for the heavy lifting.
^ open ticket, figurate numbers and sums of powers
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 (10) evals 5 16 8 4 2 1 collatz_sequence_generate (27) evals 27 82 41 124 62 31 ....
Draft. The Collatz Sequence has several applications and implications in mathematics and computer science:
The Collatz Sequence, also known as the 3n + 1 problem, is a mathematical sequence that starts with a positive integer n and follows a specific rule: if n is even, divide it by 2; if n is odd, multiply it by 3 and add 1. The sequence continues until it reaches the number 1. The Collatz Sequences serve as a fascinating and versatile mathematical concept with applications in various fields of study. Its simplicity and complexity make it a valuable tool for exploring mathematical patterns and phenomena. The Collatz Sequence has several applications and implications in mathematics and computer science:
1. Mathematical research and Number Theory: The Collatz Conjecture, which states that the sequence will always reach the number 1 regardless of the starting integer, remains an unsolved problem in mathematics. Collatz sequences have been a subject of interest in number theory and combinatorics. Researchers study the behavior of these sequences, trying to determine if they always reach 1 for any given starting number, or if there are any patterns or properties that can be derived from them. Studying the properties of the Collatz Sequence can lead to insights into number theory and the behavior of integers.
2. Algorithm Analysis: Collatz sequences are a popular example of a simple algorithm that can be implemented on a computer to demonstrate the power and limitations of computational methods. The Collatz Sequence is often used as a benchmark for testing algorithms and computational methods. Analyzing the sequence can help researchers understand the efficiency and complexity of different algorithms.
3. Cryptography: The Collatz Sequence has been used in certain cryptographic algorithms and protocols. The unpredictable nature of these Collatz sequences can be exploited to create secure encryption schemes, random number generators, and hash functions. The iterative properties of the Collatz sequence make it a potential candidate for generating random sequences or cryptographic keys.
4. Chaos Theory: The Collatz Sequence exhibits chaotic behavior, with seemingly random fluctuations and patterns. Studying the dynamics of the sequence can provide insights into chaos theory and nonlinear systems.
5. Artificial Intelligence: Collatz sequences can be used in the development of artificial intelligence algorithms. For example, researchers have used them to study the behavior of neural networks and to develop algorithms for solving complex problems.
6. Educational Purposes: The Collatz Sequences are often used as a teaching tool in mathematics and computer science courses. Collatz sequences are a great tool for teaching basic concepts in mathematics and computer science. Collatz sequences can be used to introduce students to algorithms, recursion, and problem-solving techniques. Collatz sequences can help students understand recursion, iteration, and the concept of proof by induction.
gold 3/8/2024 Update gist. Figurate numbers are a type of mathematical sequence that can be represented geometrically. These numbers can be arranged in the form of regular, geometrical shapes or patterns, hence the term "figurate." Each figurate number corresponds to the number of points that can be arranged to form a specific geometric shape. Some common examples of figurate numbers include triangular numbers, square numbers, pentagonal numbers, hexagonal numbers, and so on. Triangular numbers, for instance, can be represented as equilateral triangles, where each successive number adds an additional row of points to form a larger triangle. Figurate numbers have various applications in mathematics, including number theory, combinatorics, and geometry. They can also be used to solve problems related to patterns, sequences, and geometric arrangements. Overall, figurate numbers provide a visual and intuitive way to understand and explore mathematical concepts.
gold 3Dec2018, pages i thought were gone are showing up, largely under Category Numerical Analysis. as s_ noted, i did not use underscores much in early titles. I must learn on to use the goose search engine better. thanks. i have some updates anyway. I will add self_help button. Revamped TCL programs will be listed as V2. The bulk of these files are being stored locally as OpenOffice file.odt files or rich field text files file.rtf, mainly for spellcheck and larger stored fonts for bad eyes. My understanding is that backup on older files are available through the Internet Archive. Like the example of the Wikipedia, i think that an automated PDF dump of the individual TCL/WIKI pages would be a useful storage item, especially if the PDF included a rack of end attachment of the original unix/ascii text data for the unique WIKI table format and the TCL programs. I am scared i will lose formatted tables copy and I have a bunch.
gold 20Mar2020, Message to Middle Eastern Linguist(s) and museum curators on clay tablets. Have made replica clay tokens and published computer programs using the Sumerian math algorithms on clay tablets. Can contribute some to your museum, if interested???? Some ancient and historic algorithms were loaded into the TCLLIB library for the Tool Control Language (TCL).
gold 3/29/2026
Note. These Snippets on Theoretical Physics are a set, not stand alones. Recommend read all of the set.
>>>>>> if can't find or link, look older files under category numerical analysis <<<<<<<< >>>>>> for some unk reason, wiki search engine does not push these files to top <<<<<<<<
test below
Babylonian Sexagesimal Notation for Math on Clay Tablets in Console Example Binomial Probability Slot Calculator Example Biruni Estimate of Earth Diameter Slot Calculator eample Chinese Fortune Casting Example Demo Chinese Sun Stick Accuracy for Console Example Command Line Calculator in Namespace Package Example Crater Production Power Law Slot Calculator Example Drake Intelligent Life Equation Slot Calculator Example Easy Eye Calculator and eTCL Slot Calculator Demo Example, Numerical Analysis Ellipse Properties Slot Calculator Example Fuel Cost Estimate Log Slot Calculator Example Generic Calculator Namespace Package Example Heat Engine Combustion and Calculator Demo Example Human Language Root Words & Lexicostatistics Calculator and eTCL Slot Calculator Demo Example, numerical analysis Mahjong_Style_Deletion Oil Molecule Length Calculator and eTCL Slot Calculator Demo Example, numerical analysis Oneliner's Pie in the Sky Paper & Felt Rolls and eTCL Slot Calculator Demo Example Penny Packing Calculator and eTCL Slot Calculator Demo Example, numerical analysis Piece wise Profits and eTCL Slot Calculator Demo Example Planet Mass Calculator and eTCL Slot Calculator Demo Example, numerical analysis Poker Probability and Calculator Demo Example Random Walk Equation Slot Calculator Example Rectangular Radio Antenna and etcl Slot Calculator Demo Example Sanskrit Number Words Handling in Formulas and Demo Calculator Example Sea Island Height Slot Calculator Example Seaching for Babylonian Triplets Slot Calculator Example Simple Reliability Slot Calculator Example Slot_Calculator_Demo Stonehenge Circle Accuracy Slot Calculator Example Stratographic Years Slot Calculator Example, Age of Earth Sumerian Equivalency Values, Ratios, and the Law of Proportions with Demo Example Calculator Sumerian Beveled Bowl Volume and eTCL Slot Calculator Demo Example Sumerian Circular Segment Coefficients and Calculator Demo Example Sumerian Coefficients at the Bitumen Works and eTCL Slot Calculator Demo Example edit Sumerian Coefficients at the Weavers Factory and eTCL Slot Calculator Demo Example Sumerian Coefficients in the Pottery Factory and Calculator Demo Example Sumerian Construction Rates and eTCL Slot Calculator Demo Example Sumerian Paint & Bitumen Coating and eTCL Slot Calculator Demo Example Sumerian Population Density and eTCL Slot Calculator Demo Example Tonnage of Ancient Sumerian Ships and Slot Calculator Demo Example
Sumerian Pottery Vessel Mass Calculator, can not find in new wiki system Babylonian Square rule for Trapezoid Area and eTCL demo example calculator, numerical analysis Indian Math Bhaskara (1) Sine formula and extensions, history of math Kahan compensated summation algorithm and Neumaier variant summation algorithm, numerical analysis Sumerian Counting Boards, multiplication operation placement strategy, and eTCL demo example, numerical analysis Babylonian Combined Work Norm Algorithm and eTCL Slot Calculator Demo Example, numerical analysis Stonehenge Circle Accuracy Slot Calculator Example Drake Intelligent Life Equation Slot Calculator Example Sumerian Equivalency Values, Ratios, and the Law of Proportions with Demo Example Calculator Piece wise Profits and eTCL Slot Calculator Demo Example Sumerian Sheep and Herd Animal Calculator and eTCL Slot Calculator Demo Example, numerical analysis Electronic Failure Rate FITS and eTCL Slot Calculator Demo Example Sumerian Seeding Rates and eTCL Slot Calculator Demo Example , numerical analysis Command Line Calculator in Namespace Package Example Example Linear Interpolation Calculator Sumerian Equivalency Values, Ratios, and the Law of Proportions with Demo Example Calculator Sumerian Beveled Bowl Volume and eTCL Slot Calculator Demo Example Population Density Rectangular City Calculator and eTCL Slot Calculator Demo Example Sales Optimal Lot Order Size and eTCL Slot Calculator Demo Example Over-21 Game Shell and eTCL Slot Calculator Demo Example , numerical analysis Sumerian Beer Ingredients and eTCL Slot Calculator Demo Example , numerical analysis Easy Eye Calculator and eTCL Slot Calculator Demo Example, Numerical Analysis Paper & Felt Rolls and eTCL Slot Calculator Demo Example Human Language Root Words & Lexicostatistics Calculator and eTCL Slot Calculator Demo Example, numerical analysis Sumerian Workday Time & Account Calculator and eTCL Slot Calculator Demo Example, numerical analysis Old Babylonian Interest Rates and eTCL demo example calculator Capsule Surface Area & Volume and eTCL demo example calculator Babylonian Square rule for Trapezoid Area and eTCL demo example calculator, numerical analysis Sumerian Coefficients at the Weavers Factory and eTCL Slot Calculator Demo Example Sumerian Population Density and eTCL Slot Calculator Demo Example
A table row is specified as a line starting and ending with a pipe (|) sign. Each row element is separated with a pipe sign too. A header row start with %| and end with |%. To color even and odd rows differently, start rows with &| and end them with |&. First column should be index number and last column should be Quibble-Notes. Last row should be Audit Window.
An example:
| Row 1 | Row 2 | Row 3 |
|---|---|---|
| a | b | c |
| d | e | f |
| a | b | c |
| d | e | f |
| AUDIT Window |
First column should be index number and last column should be Quibble-Notes. Last row should be Audit Window.
%| Index | Row 1 | Row 2 | Row 3 |Quibble Notes |% &| 1 | a | b | c | Note_1 |& &| 2 | d | e | f | Note_2 |& &| 3 | a | b | c | Note_3 |& &| 4 | d | e | f | Note_4 |& &| AUDIT Window | used for sums | + Checks | |&
First column should be index number and last column should be Quibble-Notes. Last row should be Audit Window.
Subject: ASCII Diagrams
I use ASCII diagrams to document my Tcl code and program workflow content. Developing an informal set of rules for 7-bit ASCII diagrams on Tcl code and other Pseudocode.
Provisional Rules :
(e.g., heavy use of +----------------------------------------------------------------------------------+ borders).
+----------------------------------------------------------------------------------+ /====== ---- ---- ****Figure. Program Organization **** ---- ---- /====== +----------- Maybe abbreviate or trim extra long text sentences as previous . minimal changes otherwise. I see the problem. Maybe you are using/seeing Unicode or other fonts. Output needs to be asci 7-bit. Primitive text editor here. Not sure what is standard, but I like the titles to have first letters capitililzed and remaining letters as little uncapitilized letters
I remember when my teenage sister would ask about a math problem. I would lead up and carefully explain this and that algebra proposition. But my sister would say " I just want the answer!" In most engineering problems, there is an advantage in finding the answer in an approximate solution, say slide rule accuracy or 4 significant places. For example, using the old slide rule, one would make a preliminary pencil calculation and approximate answer to set the decimal point, before using the slide rule accuracy to 4 significant places. If one thinks of TCL as primarily as a graphical gui language, then the one liners programs are best used to check the preliminary math concepts. One liners programs and initial console programs are often used to check the math concepts and generate testcases before loading the calculator gui shell.
In planning any software, it is advisable to gather a number of testcases to check the results of the graphical user interface gui program. The results of the testcases are estimated using the hand calculations and then checked in the TCL gui calculator. Pseudocode and equations are developed from the hand calculations and theory. One liners procedures and small console programs are written to check or proof the alternate subroutines or procedures, rather than keeping the unblessed code and comment lines in the main gui calculator. Finally the improved or alternate subroutines are loaded into the gui calculator. The TCL gui or slot calculator is effectively a shell program to input entries, host calculation routines, maintain housekeeping procedures, and display results. Additional significant figures are used to check the TCL calculator, not to infer the accuracy of inputs and product reports.
The beginner TCL procedure on the pi circle constant was corrected to proc pi {} {expr acos(-1)} ;# AMG. One Liners Programs should avoid using temporary variables like {set temp 3.14:if {$temp=3.14} {return 1};return $temp}. Temporary variables may cause more time delay, more complication, and possible confusion to reader. The return value of a Tcl procedure is inherited from the return value of the last command to execute within that procedure. Therefore, many uses of the return command are redundant. If one insists on temporary variables, be aware that it is perfectly legal for a proc and a variable to have the same name. You could have said "set pi [pi]". For safety and efficiency, always be sure to brace your expr-essions! Heh, I neglected to brace my expression in [pi], but that's one of the extremely rare cases where it won't matter: no spaces, no substitutions. Bracing does two things: One, when the entire expression is a single word (single argument), it can be bytecode-compiled. Two, if substitutions are performed by expr only and not Tcl itself, injection attacks are prevented. Since the expr command has an internal if conditional, ? in a?b:c sic, try using the internal if <?> in expr rather than a separate IFstatement. Avoid using separate if statements and temporary variables for brevity. The args variable is also useful tool in one liners programs for inputting multiple data or lists of words. Another strategy is to keep track of possible error checks and testcases for low, middle, and high values over the range of operation of the oneliners program. An initial check for zero division or series start at one may be installed in the expr ? conditional. A simple credit for a one liner program may use a semicolon with comment sign <;#> at statement end, which should not degrade program execution. Using the time function in TCL will give even more insights into one liners programs, also see Time. In One liners Programs Pie in the Sky, one can see the advice of GWM on the importance of timing your code and procedures. Usually, invoking math ops, TCLLIB library, and other precompiled libraries can save an average of 1/3 time over big data chores. The time savings are not always obvious on small quantities of data. Performance of one liners programs may suffer degradation due to lengthy recursion calls and limits on the number of procedure recursion calls. The shorter the script, the faster and more reliable is the script. Dependence on math operator notation, helper procedures, math check examples, degradation due to lengthy recursion calls, and special library functions should be noted in the comment lines. The examples on this wiki page include code lines that might be incompatible, inefficient, or redundant if installed in the same program. As discussed, the local math procedures in scripts and one-line procedures may not be as fast and efficient as importing mathop , mathfunc, and math, so check with the precompiled code in the TCL core and TCLLIB libraries first, then homebrew your one-line programs and scripts.
gold 10/7/2018. Technical note on TCL calculator buttons addressing the reference ASK12 of 2017-02-19 . Many complex math programs have either initialize, refresh, or reset routines to force correct behavior, using calculator buttons. Of course, a very good feature of TCL is that new variables as number types do not have to be initialized prior to use. Repeating, setting a new number variable to 0 or 1 is not necessary prior to using the variable. I confess that habits brought from prior learned languages and 40 years ago are hard to change. Most of my gui programs on this wiki have a flexible button procedure (on changing labels and resetting variables prior to calculations). Where the program defaults are recalled, canvas colors/features/variables/clear displays are reset prior to ( in push button list) calculation. The buttons on the calculator are not limited to a single action proc or single shot. A button command may call multiple statements and procs like ::ttk::button .test4 -text "Test_wild_case3" -command {clearx; refresh_canvas_x .cv; fillup 120. 12.0 15.0 1. 1. 1. 1. 104.0; set global_variable 9999.;solve_routine;printout_routine;# need semicolons here; exit}. This is effectively a separate program or subprogram installed as list of procedures in a button.
The TCL language is very flexible, and as experiments, the button may invoke a do while routine to call the listed button procs multiple times like the infinite repeater (SiFi). The button may invoke command and call procedures for a random number of times and random solutions, like nerve and muscle firings from the human brain in thought and speech (not SiFi). For cosmetics, the button may set colors, frame width, canvas objects, and variables with the random proc lpick from RS on the wiki. As long as duplicate frames, duplicate canvas, pack managers, and channels are not confused reference the original program, one can load secondary and entire procs into the button list. Returning to the conventional use of resetting variables, the button refresh and initialize tactic should work across the TCL versions, at least in the versions tested (TCL8.5, and TCL8.6).
Most of the testcases involve experiments or models, using assumptions, and rules of thumb. For the push buttons in 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 to conventional texteditor. 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 should be cleared either on the clear button or on the next solve button.
gold 5/13/2021.
closer: arjenmarkus AM
Emailed icomment from AM: I used the sample code to create two new procedures:
listPrimePairs listPrimeProgressions
The first proc listPrimePairs returns a list of pairs of primes that differ by a given number and the second proc listPrimeProgressions returns a list of arithmetic progressions of primes that differ by the given number.
This item is being surfaced with friendly and quality support at ActiveState.com
gold9/22/2021 I recently installed ActiveState TCL or ActiveTCL on Windows10. I have been working with ticket additions to tcllib math files. Maybe I am wrong, but the ActiveState installer from the ActiveState website (9/22/2021} installs the old Tcllilb content (Tcllib (tcllib-1.18) of three years ago in 2019. I tried installing the current library content from the https://sourceforge.net/projects/tcllib/ plus https://www.tcl-lang.org/software/tcllib/ . It looks like the new content Tcllib tcllib-1.20 is present now, on my local ActiveTCL copy. This installation is very tricky for a 70+ year old novice with bad eyes. And I am not sure that I installed tcllib-1.20 right. Thank You
gold9/22/2022. PS. I double checked this morning and fresh reloaded the ActiveTCL on 9/22/2021 The old library (Tcllib (tcllib-1.18) is still there in a fresh download of ActiveTCL.
gold 9/19/2021. Would a wiki category on Windows_Examples_PC or Windows_Console be worthwhile? As separate from Windows Operating system? I really like some opinions. I worked 15 years on Sun Sparcs Unix, so familiar with UNIX, but am a retired engineer now. Curious about the percentage of Unix users vs PC users vs Apple on TCL wiki. Thank You. [L14 ]& [L15 ] & [L16 ]
gold 9/12/2021
When I come in as unsigned-in , the very first edit on Sep11 comes up on screen. Collatz_Sequences (3*N+1) in Console Example Demo for TCL V2. HE and I have made a bunch of changes to file. Is there some way to update page to latest edit copy, 43 or so. Thank you.
gold 9/27/2021. Closed out. I found out the trick by myself. If one picks Save button, copy goes into holding pattern or possibly quality control. If one picks Save as Minor as Minor Edit Button, the ones current edited copy is updated and appears in current in the current files.
Screen on 9/14/2021, Collatz_Sequences_not_updated_since_9_11, see date tag on bottom
gold 6/29/2021. I am working on wiki page {https://wiki.tcl-lang.org/page/Seaching+for+Babylonian+Triplets+Slot+Calculator+Example ]. Can someone point me to a quadratic solution command or proc in TCLLIB? or TCL core. Understand, I have access to Quadratic solution procs in TCL or could write one. But I am looking at the files in TCLLIB math and don't recognize the quadratic solution proc section. Thank you.
AM There is none, if you mean to solve a second-degree equation. The references to "quadratic" in the math module are all for very different entities.
gold 7/2/2012. I'll write a small proc to solve quadratic equations and put a ticket in the TCLLIB que. There was an interesting note on the quadratic equation in [L17 ] & [L18 ] Thank you.
TCLLIB ticket 5af6381a8be0d5a87505d7e28203fe69fa2b3019 in que, dated 7/3/2021 Title: Quadratic Equation Solution, 2 reals from Muller's method
Reference [L19 ]
Possible Uses of Collatz Sequences Conjecture
Offsite query from Senior TCL Enginner. 9/22/2021 was "What are the possible computer application uses of the Collatz Sequences Conjecture?
As understood here, the Collatz Sequences Conjecture is called pure mathematics. Paul Erdos said about the Collatz conjecture: “Mathematics may not be ready for such problems.” The Collatz Sequences Conjecture is at the forefront of human mathematics. The topic of the Collatz Conjecture was rated "High Priority" by WikiProject Mathematics circa Sep2021, a collective measure of Mathematicians priorities and popularity to be sure. From what an outsider can tell, the Collatz Sequences are being generated with supercomputers and distributed computing algorithms on the numeric issues. Apparently, the Collatz Sequences are as valid a test for computing machines, parallel algorithms, and distributed computing algorithms as the 1) search for pi, 2) search for highest prime number, 3) Twin Prime Conjecture, and 4) factoring numbers. In 2020, starting values up to 2**268 approximating 2.95*1020 have been checked in the Collatz conjecture. In 2019, a paper proposed using Collatz Sequences for signal encryption, High-uncertainty audio signal encryption based on the Collatz conjecture. Other papers have mentioned the buzzwords "quantum mechanics computing" and fuzzily implied that the Collatz conjecture may be analogous to setting quantum levels in a quantum device. I am a retired engineer. I have put some queries out to the pure mathematicians.
Alan Turing created the concept of a “universal computing machine” about 1937. The seminal 1937 paper was titled: On Computable Numbers With an Application to the Entscheidungsproblem. A Turing machine is a theoretical abstraction of a computing engine, but usually is presented and resolved to a computer program on existing physical computers today. There have been a number of papers laying out concepts for Turing machines based on the Collatz Sequences Conjecture. These Turing machine concepts usually use the Collatz Sequence calculations and procedures <+,/,*> in a decision matrix and rate how the conceptual Turing machine smoothly solves for Collatz Sequences in a continuous computation loop without halts and flaws. I might point out that the original Collatz Conjecture procedures involving simple <+,/,*> operations here have been spun out into Collatz-like problems, different formula approaches, and radical looking reformulations.
ProvisionaI text. I still have some queries out to pure mathematician associations and institions Collatz Sequences uses. If they answer back, the pure mathematicians may come back with different and more authoritive uses of Collatz Sequences than the retiree brigade. link to https://wiki.tcl-lang.org/page/Collatz_Sequences+%283%2AN%2B1%29+in+Console+Example+Demo+for+TCL+V3+?V=158 .
---
Clipping off the repeating terminus of the known Collatz Sequences means the sequence is still fundamentally an infinite sequence. However, the mathematicians have changed some of the original formula to make the Collatz sequence close faster. The modified Collatz sequence does close faster and has a smaller envelope with the term (3*N+1)/2. As an analogy, this is similar to the converging and diverging of a series. The original Collatz sequence is a divergent sequence in that sense, because the Collatz sequence never closes to an exact numerical limit. Briefly, similar terms to Collatz sequences are possible as generic ($C1 * N + $C2)/2. Another breakdown in similar terms to Collatz sequences is (N+2*N+1)/2. The advantage of (4*N-1*N+1)/2 is that a fourth math operation {+-*/} is added to in the original setup {+*/}. Since I have worked more with converging series on this wiki etc, I would be interested in turning the Collatz sequences into a converging series. Possibly a Collatz sequence morfed into successive ratios like the successive Fibonacci series produce the Golden Ratio (1.618) . From the previous examples, the collatz_sequence of 5 is < 5 16 8 4 2 1 >. Converts to < 8/16 4/8 2/4 1/2 > and sum from expr { 8/16. + 4/8.+ 2/4.+ 1/2. } , 2. Possibly, sum is number of terms times half?, $ND*(1./2).
Offsite query from Senior TCL Enginner. 9/22/2021 was "What are the possible computer application uses of the Collatz Sequences Conjecture?
As understood here, the Collatz Sequences Conjecture is called pure mathematics. Paul Erdos said about the Collatz conjecture: “Mathematics may not be ready for such problems.” The Collatz Sequences Conjecture is at the forefront of human mathematics. The topic of the Collatz Conjecture was rated "High Priority" by WikiProject Mathematics circa Sep2021, a collective measure of Mathematicians priorities and popularity to be sure. From what an outsider can tell, the Collatz Sequences are being generated with supercomputers and distributed computing algorithms on the numeric issues. Apparently, the Collatz Sequences are as valid a test for computing machines, parallel algorithms, and distributed computing algorithms as the 1) search for pi, 2) search for highest prime number, 3) Twin Prime Conjecture, and 4) factoring numbers. In 2020, starting values up to 2**268 approximating 2.95*1020 have been checked in the Collatz conjecture. In 2019, a paper proposed using Collatz Sequences for signal encryption, High-uncertainty audio signal encryption based on the Collatz conjecture. Other papers have mentioned the buzzwords "quantum mechanics computing" and fuzzily implied that the Collatz conjecture may be analogous to setting quantum levels in a quantum device. I am a retired engineer. I have put some queries out to the pure mathematicians.
Alan Turing created the concept of a “universal computing machine” about 1937. The seminal 1937 paper was titled: On Computable Numbers With an Application to the Entscheidungsproblem. A Turing machine is a theoretical abstraction of a computing engine, but usually is presented and resolved to a computer program on existing physical computers today. There have been a number of papers laying out concepts for Turing machines based on the Collatz Sequences Conjecture. These Turing machine concepts usually use the Collatz Sequence calculations and procedures <+,/,*> in a decision matrix and rate how the conceptual Turing machine smoothly solves for Collatz Sequences in a continuous computation loop without halts and flaws. I might point out that the original Collatz Conjecture procedures involving simple <+,/,*> operations here have been spun out into Collatz-like problems, different formula approaches, and radical looking reformulations.
gold 9/24/2021. Provisional text. I still have some queries out to pure mathematician associations and institutions on Collatz Sequences uses. If they answer queries, the pure mathematicians may come back with different and more authoritative uses of Collatz Sequences than the retiree brigade.
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 [L20 ]. 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 and math::bigfloat 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" mathematician. 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. According to Richard Suchenwirth on TCL wiki, and quoting directly " Since the console is a TK text widget, you can use all text widget commands and options on it." Refer to [L21 ] The grid Tk widget, grid Tk widget, and Tk::button all support the panel display of the Windows10 gui here. I am still learning TCL/TK. And I can not rule out that dropping the statement "package require Tk" in the Windows10 decks might have unforeseen consequences, to include other user Windows10 machines if not my own Windows10 setup. The title of wiki page and original TCL program included words '"Console Example" and "written on Winidows10". I think that the TCL WIKI is big enough to support both UNIX and Windows10 in separate groups, modus vivendi. However, your good comments have catalyzed me. I will start looking for a graphical user interface gui or template code that is cross platform, equally accessible to UNIX and Windows10. Aside from Windows10, and TCL, I wrote about 20 years of calculator guis on Javascript and UNIX at work. The main task for me was getting the ticket on Collatz_Sequences out the door.
gold 2021-09-21. I have the TCL gui graphical user interface for Collatz_Sequences working on Windows10 Console TK widget in under 288 lines of code. Meaning, one tap on the icon of the ActiveState TCL Console gets one up and running on Windows10. The gui dependency on the ActiveState TCL and Windows10 Console Tk widget has been noted sufficiently on the page title and source code. Respectfully, I remind one that I have been out of the classroom for 50+ years, and Fortran77 classes at that. I hope I may be forgiven for a few UNIX faux pas in a Window10 Console program. I welcome others on the Wiki to proof, improve, or proof the code on UNIX machines on any independent UNIX pages. I believe that the proposed implementation of the Collatz_Sequences functions in the Tcllib will accommodate the UNIX users of TCL. Sep2021 PM quote, "ActiveTcl users are overwhelmingly on Windows (80% or so), and tend to have a high proportion of novice to intermediate users." One may infer that the UNIX users of ActiveState TCL are a very intelligent, more experienced Linux users, and very sophisticated set of TCL users, if not driving the pack. I do not have all the answers. Maybe, as one infers, the ActiveState TCL Windows10 Console and TK widgets are not the best path?
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.
gold 12Dec2018. Global variables, regular expressions, and namespaces are considered advanced features of the Tool Control Language (TCL), according to Brent Welch in Practical Programming in TCL and TK. If global variables are an advanced feature of TCL, as indexed and taught after the beginner TCL topics in most TCL textbooks, then reasonably the use of global variables should be explored and discussed on the wiki. After a number of searches on the wiki and reference books, the topics of regular expressions and namespaces are adequately explored on the wiki and available textbooks. In opinion, the use of global variables in TCL programs should not be restricted to a narrow viewpoint, and the use of global variables could be a very rich vein of interest for the advanced student of programming. As an engineer with 35 years experience in Fortran, Basic, Javascript, and other computer languages, the author is familiar with self-appointed gatekeepers and the other anonymous ad hominem methods of NDH. NDH means “not done here”, “not done here in our shop”, or “not done here in my programming style”. Global variables in TCL are equivalent to the common variable statements in Fortran and Basic. The use of global variables might be called “sideloading" for data subroutines. Ref Fortran77, the large number crunching programs with 2E5+ statements in Fortran used global variables or common variable declarations as an alternate way or “programming style” to transfer or sideload information between subroutines. The other data transfer method for subroutines was discussed by Brent Welch etc in the proc command arguments or top loading in the introductory or beginner TCL material.
gold 12Dec2018. Of course, each alternate way of data information transfer in toploading and sideloading data subroutines has its own advantages and disadvantages. As most TCL users know, TCL tends to be a more compact language than Fortran77. However, the global declarations in the small TCL graphical user interface guis written for numerical analysis on this wiki have exactly the same common variable structure and same program organization as the giant Fortran number crunchers.
gold 12Dec2018. There are two alternate methods of loading TCL subroutines, known as proc arguments (top loading) and global variables (side loading). In engineering terms, the TCL global variable methods and the Fortran common variables are an economy of scale for large programs. In other words, top loading a data subroutine for a small program with a limited number of variables and a limited number of subroutines is about as efficient as global variables (side loading). When a large program has the number of variables approaching 25 variables and the total number of subroutines approach 20 subroutines, then global variables or common variables become an more attractive alternative data transfer between subroutines and a more efficient use of the programmer's time. This principle is independent of language type, and equally true for the TCL, Fortran, and other computer languages. For example, many scientific Fortran programs had a specialized subroutine for constants, including the gravity constant, speed of light, etc. If the gravity constant was used in 15 subroutines, it was easier to declare the gravity constant as a common variable in a constants subroutine, and then make a one time change in the value of gravity constant in one subroutine of constants than making the same change for the gravity constant in 15 subroutines. If one knows than the sequence of slot variables {$side1,$side2,$side3...$side8...$side_N} and other constants are TCL global variables throughout the subroutines, one can easily refer to these global values in a specialized printout report subroutine. One can also load these global values in formulas for printout and separate calculations on the fly. For a side loading example in a new subroutine, proc newby {} {global side1 side2 side3; puts <* $side1 $side2 $side3>;return <+ $side1 $side2 $side3>}. The alternative top loading would be proc newby {side1 side2 side3} { puts <* $side1 $side2 $side3>;return <+ $side1 $side2 $side3>}. Both subroutine methods work for small TCL programs with the roughly same amount of typing. Remember in top loading, one would have to make other changes in the invoking statement or proc argument statement for the subroutine. One might point out that loading more than 25 variables in either an invoking statement or proc statement is not a trivial exercise to kept correct and cued properly. For another example, a specialized subroutine for printing out variables might use s set of global variables as proc printout {} { global side1 side2 side3; puts $side1; puts $side2; pouts <* side1 side2 side3>; puts "conversion to centimeters"; puts <* $side1_inches 2.54 >; }. A specialized printout subroutine with globals previously declared is faster in development and checking numeric formulas in experience, especially where conversion of units like inches and centimeters is useful for checking the results of the program in older textbook problems.
In opinion, a set of the same global statements in numerous routines are easier to keep organized. The condition of using global variables in method is that the user understands that not all variables are invoked over all the numerous subroutines. Therefore, in the case of multiple variables > 25 and multiple subroutines >20 in a large program, changing a constant variable in a large number of subroutines, little to do in the proc argument statements and invoking the subroutines, and the availability of the global variables throughout the program means less time spent on changes for the programmer. For terms of TCL presentation on the wiki, the slot variables could be changed inside the subroutine to recognizable names in variables for the calculations and quicker comprehension of the reader. In opinion, global variables are a more efficient use of the programmers time for a quick assembly of a working gui or installing a new working subroutine in a large TCL program.
gold 12Dec2018. The author is still learning TCL. These small TCL graphical user interface guis presented in the wiki have gone through an evolution of about twenty years, including numerous unpublished Javascript and TCL guis behind a firewall before joining the wiki. The suggestions from the wiki members have been of great help and these TCL guis have continued to improve. The guis are experimental numerical analysis in nature, and not every early TCL gui or program written over the twenty year period has the same global variable features, structured programming, or beauty spots of the TCL gui genre. The author keeps hearing that TCL is not a number crunching language or an outdated language from non-users. But in the instance of the TCL global variables, the TCL globals have the equivalence of the common statements and common variables in the data subroutines of giant Fortran number crunchers.
gold 6/15/2026 Still learning, Update for V9. A Tcl 8 >>> bad habit <<<< like writing to an undeclared variable inside a namespace block has become risky in Tcl 9. The Tcl V9 language is stricter now, so it’s better to be explicit about where a variable lives. >>>>> Use variable foo when you mean a namespace variable, or ::foo when you mean a global. <<<<< The global command still works in Tcl V9, but only when you use it deliberately and with full awareness of the scope you’re touching. Meaning, I have a rack of V8.6+ code to double check.
gold 7/16/2020, Report so far, in coordination with ActiveState Support [email protected]
gold 08Jul2020. Don't know if other members of TCL Club have this problem, but the author is having great difficulty in accessing this TCL WIKI, since the TCL WIKI and other download TCL programming sites on public WIFI are blocked in the USA. Accordingly, the USA based search engines are apparently not accessing the TCL programming sites. Frantically, the blocked TCL sites will affect the availability,promulgation, and succe$$ of the TCL language. Believe that the TCL language has much to offer mankind, if the TCL language and its amazing utility are not blocked to mankind by gatekeepers, iconoclasts, and bookburners in the USA.
many thanks for help. I am still locked out from easy access to TCL Wiki. but i will report your efforts to the TCL WIKI. Is there an address to resolve issues with ATT ? . I tried to contact ATT, but there is merry-gr on that website. thanks again,gold
Sent with ProtonMail Secure Email.
‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐ On Thursday, August 13, 2020 2:50 PM, ActiveState Support <[email protected]> wrote:
Hi Gold
I'm not sure if you've been able to work around this or have it fixed yet. I can still see "Error 1000" issues on Cloudflare though with the aliased tcl.activestate.com. Maybe that domain change is being detected as a cross-site redirection attempt and blocked for that.
I'm not clear why, but there is a difference between how wiki.tcl-lang.org and tcl.tk resolve. Maybe that was intended to work like a backup site, or maybe something is out of sync:
:~$ host tcl.activestate.com tcl.activestate.com is an alias for wiki.tcl-lang.org. wiki.tcl-lang.org has address 104.18.184.65 wiki.tcl-lang.org has address 104.18.183.65 wiki.tcl-lang.org has IPv6 address 2606:4700::6812:b841 wiki.tcl-lang.org has IPv6 address 2606:4700::6812:b741 :~$ host wiki.tcl-lang.org wiki.tcl-lang.org has address 104.18.183.65 wiki.tcl-lang.org has address 104.18.184.65 wiki.tcl-lang.org has IPv6 address 2606:4700::6812:b741 wiki.tcl-lang.org has IPv6 address 2606:4700::6812:b841
:~$ host www.tcl.tk www.tcl.tk has address 104.16.56.90 www.tcl.tk has address 104.16.33.94 www.tcl.tk has IPv6 address 2606:4700::6810:385a www.tcl.tk has IPv6 address 2606:4700::6810:215e
whois 104.16.56.90 and whois 104.16.33.94host reports that's Cloudflare. whois 104.18.183.65 and whois 104.18.184.65 also reports Cloudflare
Best regards,
Technical Support Engineer ActiveState Software
APN What URL are you using to access? The tcl.tk domain is problematic (from the blocking perspective), the official name is now wiki.tcl-lang.org. Do you have problems with that domain as well?
gold 7/11/2020. Thanks for feedback. Possibly problem is default security setting on browser or virus firewall security going into a WIFI proxy server. Realize the TCL CLUB is not a 9 to 5, but this item is really cutting down my production and access to TCL references. But the browsers are changing into complexity, pretty fast for a retiree. Quotes """ If you don't believe you should be using a proxy server: Go to the Dissenter menu > Settings > Show advanced settings… > Change proxy settings… > LAN Settings and deselect the "Use a proxy server for your LAN" checkbox. UNQuote"""" The strange thing is that I can see https://wiki.tcl-lang.org/welcome and https://sourceforge.net/projects/tcllib/ at Starbucks coffee and some "bar" WIFI's, but I can not see the TCL Wiki same at Mcdonalds, Wendy's, and some other quick stop WIFI's.
7/13/2020. trouble coming from Macdonald restaurant etc ATT WIFI?? https://login-mcd-cluster.prd.....snantx.attwifi.com/g error messege found after site log. SIC http://tcl.activestate.com/software/tcllib/tcl.activestate.com’s server IP address could not be found. Try:
Checking the connection Checking the proxy, firewall, and DNS configuration Running Windows Network Diagnostics ERR_NAME_NOT_RESOLVED
http://wfr.tcl-lang.org/ https://login.attwifi.com/blocked/blocked_page.html#?......&web_rep=%3Ctrustworthy-sites%3E&web_cat=%3Cshareware-and-freeware%3E
Hi,
7/16/2020. ActiveState hasn't hosted the Tcler's Wiki for a while. From what I see in that error message though, it looks like the ATT network has DNS entries that still point to tcl.activestate.com, whereas the other providers are using the official URL instead.
We might have had a redirect sending tcl.activestate.com to the new official URL, and that redirect might have gone out of service. I have asked our IT team to investigate.
Best regards,
GS. ActiveState Software
NEW! ActiveState Platform: Build - Certify - Resolve Login to get your ActivePerl/Python/Tcl builds: https://platform.activestate.com/ .
gold 7/16/2020, end of file
# pseudocode on Babylonian triplets
2m, m**2 - 1, m**2 + 1 Babylonian triplet
twin prime number.
twin prime numbers separated by 2,4,6 ...?
c**2= a**2 + b**2
c**2= a**2 + 1 normalized Babylonian triplet
a**2 = c**2 -1 normalized Babylonian triplet
some b and c are both primes.
some b and c are not both primes.
The reciprocal pair relationship.
(X+1/X)**2 - (X+1/X)**2 = 4 , divide equation by 4
normalized triplet, < (1/4)* ((X+1/X)**2 ) , 1 ,(1/4)* ((X+1/X)**2) >
0 < X-1/X < 2
1< X-1/X < 1+sqrt(2) ~~ approximate limit of 2.4
The Babylonian regular numbers between 0 and 60 have a limited set of triplets that
satisfy 1< X-1/X < 1+sqrt(2) which appears to be the role of Plimpton 322.
The limit 1< X-1/X < 1+sqrt(2) may explain the 1<X<2 limit on the Late Babylonian
many place reciprocal tablets.
d=6 even number, l = divisor of d**2 with integer result, Babylonian triplet method
a=l+b
b= d+ (d**2)//(2*l)
c= d+l+(d**2)/(2*l)
# supposed to work for all even dNew report indicates that binary numbers and base 3 may a bit biased in the near field. But don't think the sample is large enough in this trial program.
# Pretty print version from autoindent
# and ased editor
# Possible Bias of base 2 and 3 in near field?
# written on Windows 10 on TCL
# working under TCL version 8.6
# on TCL Club , 18aug2020
# relative frequency of indiv. "throw" over all "throws".
# pi mantissa used here
# proc base and frombase by RS
package require Tk
console show
# proc base by RS
proc base {base number} {
set negative [regexp ^-(.+) $number -> number] ;# (1)
set digits {0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N
O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p
q r s t u v w x y z}
set res {}
while {$number} {
set digit [expr {$number % $base}]
set res [lindex $digits $digit]$res
set number [expr {$number / $base}]
}
if $negative {set res -$res}
set res
}
# proc base by RS
proc frombase {base number} {
set digits {0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N
O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p
q r s t u v w x y z}
set negative [regexp ^-(.+) $number -> number]
set res 0
foreach digit [split $number ""] {
set decimalvalue [lsearch $digits $digit]
if {$decimalvalue<0 || $decimalvalue >= $base} {
error "bad digit $decimalvalue for base $base"
}
set res [expr {$res*$base + $decimalvalue}]
}
if $negative {set res -$res}
set res
}
proc calculation { facen } {
# prob. subroutines for mimic sequence of bronze
# prob. is throw combos of eg. "7" over all possible throws
# set lister [split {14159265358979323846} ""]
# in base 3 10111100001122100002122202221020002210001
# in base 2 1100010001111111110100001101001100110010011101001101011111000110
set target [ base 3 14159265358979323846 ]
set lister [split { 1100010001111111110100001101001100110010011101001101011111000110 } ""]
set ee [llength $lister ]
set kk [ llength [ lsearch -all $lister $facen ] ]
set prob [ expr { ($kk*1.) / $ee } ]
return $prob
}
set limit 12
puts "%|table| printed in|TCL format |% "
puts "&| quantity| value| comment, if any|& "
for { set i 0 } { $i <= $limit } { incr i } {
lappend listxxx $i
lappend listxxx [ calculation $i ]
puts " &| $i | [ calculation $i ] | |&"
}
#end
puts " [ base 2 14159265358979323846 ] "| table | printed in | TCL format |
|---|---|---|
| quantity | value | comment, if any |
| 0 | 0.4461538461538462 | |
| 1 | 0.5384615384615384 | |
| 2 | 0.0 | |
| 12 | 0.0 | 1100010001111111110100001101001100110010011101001101011111000110 |
binary pi in 512 places. 11. 0010010000111111011010101000100010000101101000110000100011010011 0001001100011001100010100010111000000011011100000111001101000100 1010010000001001001110000010001000101001100111110011000111010000 0000100000101110111110101001100011101100010011100110110010001001 0100010100101000001000011110011000111000110100000001001101110111 1011111001010100011001101100111100110100111010010000110001101100 1100000010101100001010011011011111001001011111000101000011011101 0011111110000100110101011011010110110101010001110000100100010111
| table | printed in | TCL format |
|---|---|---|
| quantity | value | comment, if any |
| 0 | 0.5394990366088632 | binary pi in 510 digits |
| 1 | 0.44701348747591524 | |
| 2 | 0.0 |
# adapted from tcl-wiki Stats 2011-05-22, arithmetic mean [RLE]
#
# ::math::quantity_into_ratios --
#
# Return the division of quantity by two or more given ratios
#
# Arguments:
# val first value is quantity
# args other values are two or more given ratios
#
# Results: parts of quantity divided by ratios
#
proc ::math::quantity_into_ratios {quantity args} {
set sum 0.
set N [ expr { [ llength $args ] + 1 } ]
if { $N == 1 } { return 0 }
foreach val $args {
set sum [ expr { $sum + $val } ]
}
foreach val $args {
lappend answer [ expr { $quantity * ($val/$sum) } ]
}
set answer
}
#puts " ::math::quantity_into_ratios ( 84 2 2 2 ) answer 12.0 24.0 48.0 "
#puts " [ ::math::quantity_into_ratios 84 1 2 4 ] "
#puts " [ ::math::quantity_into_ratios 84 ] for (::math::quantity_into_ratios 84) returns zero " # adapted from tcl-wiki Stats 2011-05-22, arithmetic mean [RLE]
#
# sqrt_sum_of_squares --
#
# Return the sqrt_sum_of_squares by one or more
#
# Arguments:
#
# args other values are one or more
#
# Results: sqrt_sum_of_squares
#
proc sqrt_sum_of_squares { args} {
set sum 0.
set N [ expr { [ llength $args ] + 1 } ]
if { $N == 1 } { return 0 }
foreach val $args {
set sum [ expr { $sum + $val*$val } ]
}
set answer [ expr { sqrt($sum) } ]
}
#puts " ::math::sqrt_sum_of_squares ( 2 2 2 ) answer [sqrt 12 ]
# 3.4641016151377544
#puts " [ ::math::sqrt_sum_of_squares 1 2 4 ] "
#puts " [ ::math::sqrt_sum_of_squares 2 ] for ( ) returns zero "
console show
console eval {.console config -bg palegreen}
console eval {.console config -font {fixed 20 bold}}
console eval {wm geometry . 40x20}
puts " sqrt_sum_of_squares 2 2 2 equals [ sqrt_sum_of_squares 2 2 2 ]"
puts " sqrt_sum_of_squares 1 1 1 equals [ sqrt_sum_of_squares 1 1 1 ]"
puts " sqrt_sum_of_squares 1 1 equals [ sqrt_sum_of_squares 1 1 ]"
puts " sqrt_sum_of_squares 1 equals [ sqrt_sum_of_squares 1 ]"
puts " sqrt_sum_of_squares 0 equals [ sqrt_sum_of_squares 0 ]"sqrt_sum_of_squares 2 2 2 equals 3.4641016151377544 sqrt_sum_of_squares 1 1 1 equals 1.7320508075688772 sqrt_sum_of_squares 1 1 equals 1.4142135623730951 sqrt_sum_of_squares 1 equals 1.0 sqrt_sum_of_squares 0 equals 0.0
From Discrete event modelling with coroutines by Author : Arjen Markus (21 april 2009). Added easy eye console for my bad eyes.
# coro_discrete_events.tcl --
# Experiment with SIMULA/DEMOS like modelling - using coroutines
# from Discrete event modelling with coroutines
# Author : Arjen Markus (21 april 2009)
# Discrete event modelling is a way of modelling all manner of systems
package require Tcl 8.6
# acquire --
# Acquire resources and wait if that does not succeed
#
# Arguments:
# name Name of the resource
# amount Amount to acquire
#
# Returns:
# None
#
# start modifications
package require math::numtheory
package require math::constants
package require math::trig
package require math
namespace path {::tcl::mathop ::tcl::mathfunc math::numtheory math::trig math::constants }
set tclprecision 17
console show
# following dresses up console output to easy eye
console eval {.console config -bg palegreen}
console eval {.console config -font {fixed 20 bold}}
console eval {wm geometry . 40x20}
console eval {.console config -background palegreen -highlightcolor tan -relief raised -border 30 }
# changes: shifted text, removed empty lines, added easy eye console to deck.
# changes: ran text through autoindent of ASED TCL editor
# end modifications
proc acquire {name amount} {
upvar 1 objectID ID
upvar #0 $name resource_name
puts "Acquiring $amount of $name for $ID ..."
if { $resource_name >= $amount } {
set resource_name [expr {$resource_name - $amount}]
} else {
puts "Waiting for $name -- $ID"
while {1} {
set ::queue($name) [linsert $::queue($name) 0 $ID]
yield [list acquire $name $ID]
puts "Checking $name ..."
if { $resource_name >= $amount } {
set resource_name [expr {$resource_name - $amount}]
break
}
puts "Wait again - $name - $resource_name -- $amount ..."
}
}
puts "Acquired $amount of $name for $ID"
}
# release --
# Release resources
#
# Arguments:
# name Name of the resource
# amount Amount to release
#
# Returns:
# None
#
proc release {name amount} {
upvar 1 objectID ID
upvar #0 $name resource_name
set resource_name [expr {$resource_name + $amount}]
puts "Releasing $amount of $name for $ID"
if { [llength $::queue($name)] != 0 } {
set hid [lindex $::queue($name) 0]
set ::queue($name) [lrange $::queue($name) 1 end]
set ::events [linsert $::events 0 [list $hid acquire 0.0]]
}
puts "Released $amount of $name for $ID"
}
# resource --
# Create a named resource
#
# Arguments:
# name Name of the resource
# amount Amount to create
#
# Returns:
# None
#
proc resource {name amount} {
upvar #0 $name resource_name
set resource_name $amount
set ::queue($name) {}
}
# hold --
# Advance the time for the given object in the simulation
#
# Arguments:
# delay Time to advance
#
# Returns:
# None
#
proc hold {delay} {
upvar 1 objectID object
lappend ::events [list $object "hold" [expr {$::time+$delay}]]
puts "Holding for $delay seconds ... $object"
yield
puts "Done"
}
# object --
# Create an object and schedule it's coming alive
#
# Arguments:
# procedure Name of the procedure holding the life cycle
# time Time at which it comes alive
#
# Returns:
# Structure representing the object
#
proc object {procedure time} {
set obj [list $procedure $::objectno]
lappend ::events [list $obj "init" $time]
incr ::objectno
return $obj
}
# handleEvents --
# Handle the events that were scheduled
#
# Arguments:
# None
#
# Returns:
# None
#
proc handleEvents {} {
global time
global events
while { [llength $events] > 0 } {
set count 0
set found 0
foreach event $events {
foreach {obj type eventTime} $event {break}
if { $eventTime <= $time } {
set events [lreplace $events $count $count]
set found 1
break
}
incr count
}
if { ! $found } {
foreach {obj type eventTime} [lindex $events 0] {break}
set events [lrange $events 1 end]
}
if { $time < $eventTime } {
set time $eventTime
}
if { $type == "init" } {
coroutine [lindex $obj 1] {*}$obj
}
if { $type == "hold" } {
puts "Releasing hold: $obj"
$obj
}
if { $type == "acquire" } {
puts "Continue acquiring: $obj"
$obj
}
}
}
# startSimulation --
# Start the simulation
#
# Arguments:
# None
#
# Returns:
# None
#
proc startSimulation {} {
if { [llength $::events] == 0 } {
return
} else {
handleEvents
}
}
# boat --
# Simulate a boat that requires several tugs to get into the harbour
#
# Arguments:
# objectID ID of the object (required name!)
#
# Returns:
# None
#
proc boat {objectID} {
acquire tugs 2
hold 10
release tugs 2
}
# main --
# Simulate two objects that need the same resources
#
# Initialise simulation system
set objectno 0
set time 0.0
set events {}
# The simulation itself
resource tugs 3
set b1 [object boat 1.0]
set b2 [object boat 4.0]
startSimulationgold 9/10/2020. added pix.
Beginning in the sixties, the one liner program was typed input to the command line of an operating computer system terminal so that the one line command performs some useful function in a single one line of terminal input. Some of the original one liner commands were limited to a 60 character display on especially the early Basic terminals or to a 72 characters on the Fortran punched cards. Of course, the hit return to send, terminal flashing bulbs, and automatic answer back were silently understood as part or supporting the one liner program. Some of the line lengths in some computer languages were later extended to 410 lines and so on. The definition and use of the one liner program has been widened to include program source for any language that does something useful in one line. On batch programs, controlling and setting variable statements like RETURN, STOP, END, extra terminal prompts, and setting initial variables were used in Fortran systems. Of course, a very good feature of TCL is that new variables as number types do not have to be initialized prior to use and no subroutine RETURN and END statements are necessary, vis the older Fortran and Basic dogmas in moldy textbooks. Repeating, setting a new number variable to 0 or 1 is not necessary prior to using the variable. Since a partial and practical goal of computer programming is to produce human readable code, it is permissible on the published console batch programs here to retain some vestigial stages to aid human comprehension.
# pretty print from autoindent and ased editor
# Timing Equivalent One Liners V2
# written on Windows 10 on eTCL
# working under TCL version 8.6
# gold on TCL Club , 8/20/2020
# Ref. WIKI BOOKS, Tcl_Programming_Introduction
# Book Section contrasts one liners
# versus traditional procedural approach
# below contains redundant procs
package require Tk
package require math::numtheory
package require math::constants
package require math::trig
package require math
namespace path {::tcl::mathop ::tcl::mathfunc math::numtheory math::trig math::constants }
set tcl_precision 17
proc pie {} {return [expr acos(-1)]}
console show
console eval {.console config -bg palegreen}
console eval {.console config -font {fixed 20 bold}}
console eval {wm geometry . 40x20}
# uses join, but computer time on some?
proc mean_1 list {expr double([join $list +])/[llength $list]}
# math operators exposed as commands, and the expand operator
proc mean_2 list {expr {[tcl::mathop::+ {*}$list]/double([llength $list])}}
# import the tcl::mathop operators
proc mean_3 list {expr {[+ {*}$list]/double([llength $list])}}
# import the tcl::mathop operators from <Summing a list>
# list add ladd or summing a list
proc ladd_1 {listx} {::tcl::mathop::+ {*}$listx}
# using join in ladd_2 from RS
proc ladd_2 {listx} {expr [join $listx +]+0} ;# RS
# using expr including non integers from PYK 2016-04-13
proc ladd_3 {listx} {set total 0.0; foreach nxt $listx {set total [expr {$total + $nxt}]}; return $total}
set limit 12
puts "%|table| | printed in|TCL format |% "
puts "&| session| proc & mean value| elements in list | comment, if any|& "
for { set i 0 } { $i <= $limit } { incr i } {
set lister { 1 2 4 5 6 7 8 9 10 }
lappend lister [* $i [pie]]
puts "&|$i | ladd_1 [ ladd_1 $lister ] | $lister | proc timer [ time { set qq [ ladd_1 $lister ]} 5000 ] |&"
puts "&|$i | ladd_2 [ ladd_2 $lister ] | $lister | proc timer [ time { set qq [ ladd_2 $lister ]} 5000 ] |&"
puts "&|$i | ladd_3 [ ladd_3 $lister ] | $lister | proc timer [ time { set qq [ ladd_3 $lister ]} 5000 ] |&"
puts "&|$i | mean_1 [ mean_1 $lister ] | $lister | proc timer [ time { set qq [ mean_1 $lister ]} 5000 ] |&"
puts "&|$i | mean_2 [ mean_2 $lister ] | $lister | proc timer [ time { set qq [ mean_2 $lister ]} 5000 ] |&"
puts "&|$i | mean_3 [ mean_3 $lister ] | $lister | proc timer [ time { set qq [ mean_3 $lister ]} 5000 ] |&"
puts "&|$i | ::math::mean [::math::mean 1 2 4 5 6 7 8 9 10 [* $i [pie]]] | $lister | proc timer [ time { set qq [ ::math::mean 1 2 4 5 6 7 8 9 10 [* $i [pie]] 5000 ]} ] |&"
}
#end | table | printed in | TCL format | |
|---|---|---|---|
| session | proc & mean value | elements in list | comment, if any |
| 0 | ladd_1 52.0 | 1 2 4 5 6 7 8 9 10 0.0 | proc timer 2.3273999999999999 microseconds per iteration |
| 0 | ladd_2 52.0 | 1 2 4 5 6 7 8 9 10 0.0 | proc timer 5.6311999999999998 microseconds per iteration |
| 0 | ladd_3 52.0 | 1 2 4 5 6 7 8 9 10 0.0 | proc timer 4.3941999999999997 microseconds per iteration |
| 0 | mean_1 5.2000000000000002 | 1 2 4 5 6 7 8 9 10 0.0 | proc timer 13.053599999999999 microseconds per iteration |
| 0 | mean_2 5.2000000000000002 | 1 2 4 5 6 7 8 9 10 0.0 | proc timer 3.0369999999999999 microseconds per iteration |
| 0 | mean_3 5.2000000000000002 | 1 2 4 5 6 7 8 9 10 0.0 | proc timer 2.3805999999999998 microseconds per iteration |
| 0 | ::math::mean 5.2000000000000002 | 1 2 4 5 6 7 8 9 10 0.0 | proc timer 22 microseconds per iteration |
| 1 | ladd_1 55.141592653589797 | 1 2 4 5 6 7 8 9 10 3.1415926535897931 | proc timer 1.7847999999999999 microseconds per iteration |
| 1 | ladd_2 55.141592653589797 | 1 2 4 5 6 7 8 9 10 3.1415926535897931 | proc timer 7.3037999999999998 microseconds per iteration |
| 1 | ladd_3 55.141592653589797 | 1 2 4 5 6 7 8 9 10 3.1415926535897931 | proc timer 1.7285999999999999 microseconds per iteration |
| 1 | mean_1 5.5141592653589795 | 1 2 4 5 6 7 8 9 10 3.1415926535897931 | proc timer 8.3374000000000006 microseconds per iteration |
| 1 | mean_2 5.5141592653589795 | 1 2 4 5 6 7 8 9 10 3.1415926535897931 | proc timer 2.2898000000000001 microseconds per iteration |
| 1 | mean_3 5.5141592653589795 | 1 2 4 5 6 7 8 9 10 3.1415926535897931 | proc timer 2.1674000000000002 microseconds per iteration |
| 1 | ::math::mean 5.5141592653589795 | 1 2 4 5 6 7 8 9 10 3.1415926535897931 | proc timer 6 microseconds per iteration |
| 2 | ladd_1 58.283185307179586 | 1 2 4 5 6 7 8 9 10 6.2831853071795862 | proc timer 1.7618 microseconds per iteration |
| 2 | ladd_2 58.283185307179586 | 1 2 4 5 6 7 8 9 10 6.2831853071795862 | proc timer 6.6627999999999998 microseconds per iteration |
| 2 | ladd_3 58.283185307179586 | 1 2 4 5 6 7 8 9 10 6.2831853071795862 | proc timer 4.0709999999999997 microseconds per iteration |
| 2 | mean_1 5.8283185307179588 | 1 2 4 5 6 7 8 9 10 6.2831853071795862 | proc timer 8.5307999999999993 microseconds per iteration |
| 2 | mean_2 5.8283185307179588 | 1 2 4 5 6 7 8 9 10 6.2831853071795862 | proc timer 2.1261999999999999 microseconds per iteration |
| 2 | mean_3 5.8283185307179588 | 1 2 4 5 6 7 8 9 10 6.2831853071795862 | proc timer 2.3512 microseconds per iteration |
| 2 | ::math::mean 5.8283185307179588 | 1 2 4 5 6 7 8 9 10 6.2831853071795862 | proc timer 5 microseconds per iteration |
| 3 | ladd_1 61.424777960769376 | 1 2 4 5 6 7 8 9 10 9.4247779607693793 | proc timer 1.9702 microseconds per iteration |
| 3 | ladd_2 61.424777960769376 | 1 2 4 5 6 7 8 9 10 9.4247779607693793 | proc timer 7.1285999999999996 microseconds per iteration |
| 3 | ladd_3 61.424777960769376 | 1 2 4 5 6 7 8 9 10 9.4247779607693793 | proc timer 2.6114000000000002 microseconds per iteration |
| 3 | mean_1 6.1424777960769372 | 1 2 4 5 6 7 8 9 10 9.4247779607693793 | proc timer 8.5581999999999994 microseconds per iteration |
| 3 | mean_2 6.1424777960769372 | 1 2 4 5 6 7 8 9 10 9.4247779607693793 | proc timer 2.1989999999999998 microseconds per iteration |
| 3 | mean_3 6.1424777960769372 | 1 2 4 5 6 7 8 9 10 9.4247779607693793 | proc timer 2.4533999999999998 microseconds per iteration |
| 3 | ::math::mean 6.1424777960769372 | 1 2 4 5 6 7 8 9 10 9.4247779607693793 | proc timer 5 microseconds per iteration |
| 4 | ladd_1 64.566370614359172 | 1 2 4 5 6 7 8 9 10 12.566370614359172 | proc timer 1.7842 microseconds per iteration |
| 4 | ladd_2 64.566370614359172 | 1 2 4 5 6 7 8 9 10 12.566370614359172 | proc timer 10.103400000000001 microseconds per iteration |
| 4 | ladd_3 64.566370614359172 | 1 2 4 5 6 7 8 9 10 12.566370614359172 | proc timer 1.9608000000000001 microseconds per iteration |
| 4 | mean_1 6.4566370614359174 | 1 2 4 5 6 7 8 9 10 12.566370614359172 | proc timer 8.8523999999999994 microseconds per iteration |
| 4 | mean_2 6.4566370614359174 | 1 2 4 5 6 7 8 9 10 12.566370614359172 | proc timer 2.0948000000000002 microseconds per iteration |
| 4 | mean_3 6.4566370614359174 | 1 2 4 5 6 7 8 9 10 12.566370614359172 | proc timer 2.2736000000000001 microseconds per iteration |
| 4 | ::math::mean 6.4566370614359174 | 1 2 4 5 6 7 8 9 10 12.566370614359172 | proc timer 5 microseconds per iteration |
| 5 | ladd_1 67.707963267948969 | 1 2 4 5 6 7 8 9 10 15.707963267948966 | proc timer 3.6421999999999999 microseconds per iteration |
| 5 | ladd_2 67.707963267948969 | 1 2 4 5 6 7 8 9 10 15.707963267948966 | proc timer 10.6218 microseconds per iteration |
| 5 | ladd_3 67.707963267948969 | 1 2 4 5 6 7 8 9 10 15.707963267948966 | proc timer 2.3553999999999999 microseconds per iteration |
| 5 | mean_1 6.7707963267948967 | 1 2 4 5 6 7 8 9 10 15.707963267948966 | proc timer 8.4225999999999992 microseconds per iteration |
| 5 | mean_2 6.7707963267948967 | 1 2 4 5 6 7 8 9 10 15.707963267948966 | proc timer 2.1343999999999999 microseconds per iteration |
| 5 | mean_3 6.7707963267948967 | 1 2 4 5 6 7 8 9 10 15.707963267948966 | proc timer 2.1093999999999999 microseconds per iteration |
| 5 | ::math::mean 6.7707963267948967 | 1 2 4 5 6 7 8 9 10 15.707963267948966 | proc timer 5 microseconds per iteration |
set strinit “123456789”
proc string_end strin5 { string index $strin5 end}
string_end $strinit
# out 9
proc sea5 bb { set i 2;if {$i < 10} { while {$i < 5} { puts [incr i]}}}
sea 5
# return first character of string
proc string_end5 bb { string index $bb 0 }
# return last character of string
proc string_end5 bb { string index $bb end }
# Enter number num for next above power of 2, John K. Ousterhout, Tcl and the Tk Toolkit
proc near_above_power_of_2 num {set pow 1; while {$pow<$num} {set pow [expr { $pow*2} ]}; return $pow}
# Usage near_above_power_of_2 7 returns 8,
# Usage near_above_power_of_2 9 returns 16,
# Usage near_above_power_of_2 99999999999999 140737488355328
# Enter number num for next below power of 2, John K. Ousterhout, Tcl and the Tk Toolkit
proc near_below_power_of_2 num {set pow 1; while {$pow< [expr {$num - 1}] } {set pow [expr { $pow*2} ]}; return [expr { $pow*.5} ]}
# Usage near_below_power_of_2 7 returns 4. # start advice file.
AMG: The return value of a Tcl procedure is inherited from the return value of the last command to execute within that procedure. Therefore, many uses of the [return] command are redundant. For example, this procedure:
proc anglecosa {a b c} {return [expr {($b*$b+$c*$c-$a*$a)/(2.*$b*$c)}]}
can be written more simply:
proc anglecosa {a b c} {expr {($b*$b+$c*$c-$a*$a)/(2.*$b*$c)}}
Also, the conditional arguments to [if], [while], [for] are already expr-essions, so there's no need to nest a call to [expr]. For example,
proc emmy2 {} {if {[expr {rand()}] <= 0.9} {return 1}}
can be simplified quite a lot:
proc emmy2 {} {if {rand() <= 0.9} {return 1}}
#end of advice file # TCL source code follows
# ASED autoindent applied
# Trial Console Program brackets and quotes.
# written on Windows XP on TCL
# working under TCL version 8.6
# gold on TCL Club, 12Dec2018
console show
puts " result value is [expr { 1+3} ] ";
puts [expr { 1+3} ];
# creating list
set lister1 [ list dog cat lizard ] ;
puts $lister1;
set lister2 {" dog cat lizard" };
puts $lister2;
# $lister2 is really a string of 3 items
# but some list coomands lappend and lindex may
# interpret $lister2 as list
set lister3 {" dog cat” lizard };
puts $lister3;
set lister4 " dog cat lizard" ;
$lister4;
# note outputs are similar
# for $lister1 and $lister4
# gold on TCL Club, 12Dec2018
gold 9/24/2021. updated examples
# The easy way is to start with proper list command
set list_fruit [ list apple pear orange grape ]
lappend $list_fruit peach
# The hard way is to start with individual strings of characters
set a1 apple
set a2 pear
set a3 orange
set a4 grape
set a5 peach
set list_fruit_assembly [ list $a1 $a2 $a3 $a4 ]
lappend list_fruit_assembly $a5
# begin code for TCL wiki table format
proc wiki_table_format { start finish } {
# TCL wiki table format
# set numers in TCL wiki table format
# use equivalent TCL procedure all the time for tables in wikis
set first $start
set last $finish
set list_numbers [ list &| ]
while {$first < $last } {
lappend list_numbers entry No. $first = $first |
incr first
}
lappend list_numbers comments |&
puts $list_numbers
# &| entry No. 1 = 1 | entry No. 2 = 2 | entry No. 3 = 3 | entry No. 4 = 4 | entry No. 5 = 5 | entry No. 6 = 6 | entry No. 7 = 7 | entry No. 8 = 8 | entry No. 9 = 9 | comments |& }
wiki_table_format 1 10
# &| 8191 24574 12287 36862 :| collatz_sequence_head : | | |& /
&| 8 4 2 1 :| collatz_sequence_tail : | | |& /
&| 159 :| collatz_sequence_length: | | |&scratch
proc near_above_power_of_2x num {set pow 1; while {$pow<$num} {set pow [expr { $pow*2} ]}; return $pow}
proc near_above_power_of_2 num {set pow 1; while {$pow<$num} {set pow [expr { $pow*2} ]}; return $pow}
proc ld x "expr {log(\$x)/[expr log(2)]}" ;# RS
[pow 2 [+ [int 2.8] 1]]= "8.0"
proc zap x "[pow 2 [+ 1 [expr {log(\$x)/[expr log(2)]}]"
proc zap x "pow 2 [+ [int 2.8] 1]" #under test from www.codecodex.com/wiki
set lister { 1 2 4 5 6 7 8 9 10 }
set s {starchild}
package require struct::list
proc reverseWords s {return [struct::list reverse [split $s]]}
proc ! n {expr {$n<2? 1: $n*[! [incr n -1]]}}
# usage ! 5 returns 120
proc average list {expr ([join $list +])/[llength $list].}
for {set i 1} {$i <= 1000} {incr i} {pust [expr {$i*($i+1)/2}]}
namespace import ::tcl::mathop::*
proc average list {expr {[+ {*}$list]/double([llength $list])}}
# works here , average $lister returns 5.777777777777778
proc fib n {expr {$n<2? $n: [fib [incr n -1]] + [fib [incr n -1]]}}
# not working here
namespace import ::tcl::mathfunc::*
::tcl::mathfunc::isqrt 26
# ::tcl::mathfunc::isqrt 26 returns 5, working here
set date [clock format [clock scan $date] -format {%Y-%m-%d %H:%M:%S}] ;#dclaar
scriptEval clock format [clock scan $tDate] -format {%Y-%m-%d %H:%M:%S} ;#dclaar
# clock scan is your friend; it knows all sorts of formats. In
# case above, it converts: Oct 15 06:52:45 2009 to: 2009-10-15 06:52:45 # pretty print from autoindent and ased editor
# list_twin_primes V2
# written on Windows 10 on TCL
# working under TCL version 8.6
# gold on TCL Club , 8/20/2020
# Ref. WIKI BOOKS, Tcl_Programming_Introduction
# Book Section contrasts one liners
# versus traditional procedural approach
# below contains redundant procs
package require Tk
package require math::numtheory
package require math::constants
package require math::trig
package require math
namespace path {::tcl::mathop ::tcl::mathfunc math::numtheory math::trig math::constants }
set tcl_precision 17
proc pie {} {return [expr acos(-1)]}
console show
console eval {.console config -bg palegreen}
console eval {.console config -font {fixed 20 bold}}
console eval {wm geometry . 40x20}
# invoking TCLLIB math::numtheory
proc isprimex x {expr {$x>1 && ![regexp {^(oo+?)\1+$} [string repeat o $x]]}}
# list_twin_primes proc under test, list_twin_primes and isprime procs are recursion limited
proc list_twin_primesx { aa bb cc} { for {set i $aa} {$i<=$bb} {incr i $cc} { if {[isprime $i] && [isprime [+ $i $cc ]] } {lappend boo $i [+ $i $cc ] } } ; return $boo}
proc list_twin_primes { aa bb cc} { for {set i $aa} {$i<=$bb} {incr i 1} { if {[isprime $i] && [isprime [+ $i $cc ] ] } { lappend boo $i [+ $i $cc ] } } ; return $boo}
# aa is start number, bb is upper limit, cc is separator number, usually even 2
# The original Dickson conjecture has separator even numbers 2,4,6 ... ?
# list_twin_primes 0 25 2 returns 3 5 5 7 11 13 17 19
# The sets <13 15> and <15 17> are separated by a even 2,
# but left out of answer.
# Note the 15 is not a prime number and has factors <3 5>.
# The set <13 17> has two primes, but separated by an even 4.
# reference On-Line Encyclopedia of Integer Sequences website
# OEIS A077800 discussed that the twin prime sets <p,p+2> are
# (3, 5), (5, 7), (11, 13), (17, 19),
# (29, 31), (41, 43), (59, 61), (71, 73),
# (101, 103), (107, 109), (137, 139)...
# OEIS A275021 has samples of <p,p+4> and omits pairs of <p,p+2>
# 79, 83, 127, 131, 163, 167, 379, 383, 397, 401, 439, 443,...
# list_twin_primes 75 135 4 returns 79 83 103 107 127 131
# reference On-Line Encyclopedia of Integer Sequences website
# OEIS A023201 has some samples of <p,p+6>
# 5, 7, 11, 13, 17, 23, 31, 37,
# 41, 47, 53, 61, 67, 73, 83, 97, 101
# contains redundant procs for testing
puts "[list_twin_primes 3 25 2 ]"
puts "[list_twin_primes 3 25 4 ]"
puts "[list_twin_primes 3 25 6 ]"| table | Twin Primes for 2,4,6,10 Separators | printed in | TCL format | |
|---|---|---|---|---|
| result | lower limit | upper limit | separator integer | comment, if any |
| elements in list | lower limit | upper limit | separator integer | comment, if any |
| 3 5 5 7 11 13 17 19 | 3 | 25 | 2 | |
| 3 7 7 11 13 17 19 23 | 3 | 25 | 4 | |
| 5 11 7 13 11 17 13 19 17 23 23 29 | 3 | 25 | 6 | |
| 3 13 7 17 13 23 19 29 | 3 | 25 | 10 |
gold Here are some one line procedures for circle area and law of cosines. See tcl::mathfunc cos pi constants Functions ::math::constants::constants and ::math::fibonacci are available in the TCLLIB.
proc pi {} {expr {acos(-1)}} #from AMG see below
proc degtoradiansconst {} {return [ expr {180./[pi]} ]}
proc degz {} {return [ expr {180./[pi]} ]}
proc degx {aa} {return [ expr { [degz]*acos($aa) } ]}
proc inrad {a b c} {return [expr {(sqrt(($a+$b+$c)*($a+$b-$c)*($a-$b+$c)*($b+$c-$a)))/(2.*($a+$b+$c)) } ] }
proc circlediameter {radius} { return [ expr { 2.* $radius } ] }
proc circlearea {radius} { return [ expr { [pi]*($radius**2) }]}
proc circlecircumference {radius} {return [ expr {2.*[pi]*$radius }]}
proc spherediameter {radius} {return [ expr { 2.* $radius }]}
proc spherevolume {radius} { return [ expr { (4./3.)*[pi]*($radius**3) }]}
proc spheresurface {radius} { return [ expr { 4.*[pi]*($radius**3) }]}
proc cubevolume {aa} { return [ expr { 1.*$aa*$aa*$aa } ] }
proc squarearea {aa} { return [ expr { 1.*$aa*$aa } ] }
proc ellipsoidvolume {aa bb cc} { return [ expr { 1.*(4./3.)*[pi]*$aa*$bb*$cc } ] }
proc ellipsearea1 { aa bb } {return [ expr { 1.*[pi]*$aa*$bb } ]}
proc ellipseperimeterx {aa bb} { set tt [ expr { ($aa*$aa+$bb*$bb)/2.}];return [ expr { 2.*[pi]*sqrt($tt)} ] }
proc spherevolumex {aa } { return [ expr { 1.*(4./3.)*[pi]*$aa*$aa*$aa } ] }
proc spheroidvolumex {aa cc } { return [ expr { 1.*(4./3.)*[pi]*$aa*$aa*$cc } ] }
proc torusvolumex {aa bb } { return [ expr {(1./4.) *[pi]*[pi] * ($aa + $bb) * ($aa - $bb)*2.}] }
proc torussurfacex {aa bb } { return [ expr { [pi]*[pi] * ($aa*$aa - $bb*$bb) }] }
proc conesurfacex {aa rr } { return [ expr { [pi]*$rr*$aa}] }
proc cylindersurfacesidex {aa rr } { return [ expr {2.* [pi]*$rr*$aa}] }
proc cylinderwholesurfacesidex {aa rr } { return [ expr {2.* [pi]*$rr*$aa +2.*[pi]*$rr*$rr}] }
proc cylindervolumesidex {aa rr } { return [ expr { [pi]*$rr*$rr*$aa}] }
proc conevolumex {aa rr } { return [ expr { (1./3.)*[pi]*$rr*$rr*$aa}] }
proc pyramidvolumex {aa bb cc } { return [ expr { (1./3.)*$aa*$bb*$cc }] }
proc rectangularprismvolumex {aa bb cc } { return [ expr { $aa*$bb*$cc }] }
proc triangularprismvolumex {aa bb cc } { return [ expr { $aa*$bb*$cc*.5 }] }
proc polygonperimeterx {aa bb } { return [ expr { $aa*$bb}] }
proc rectangleperimeterx {aa bb } { return [ expr {2.*( $aa+$bb)}] }
proc parallelogramperimeterx {aa bb } { return [ expr {2.*( $aa+$bb)}] }
proc triangleperimeterx {aa bb cc} { return [ expr { $aa+$bb+$cc }] }
proc triangletrapezoidx {aa bb cc} { return [ expr { $aa*($bb+$cc)*(1./2.) }] }
#law of cosines, aa bb cc are three sides of right triangle, here ordered
#as aa small side , bb middle side, cc largest side.
# inrad is radius of cirle inscribed in right triangle,
# use sides as inrad aa bb cc
proc anglecosa { aa bb cc } {return [ expr { ($bb*$bb+$cc*$cc-$aa*$aa)/(2.*$bb*$cc) }]}
proc anglecosb { aa bb cc } {return [ expr { ($cc*$cc+$aa*$aa-$bb*$bb)/(2.*$aa*$cc) }]}
proc anglecosc { aa bb cc } { return [ expr { ($aa*$aa+$bb*$bb-$cc*$cc)/(2.*$aa*$bb) }]}
#with examples
#for radius of 1
#circlediameter 1
#circlearea 1
#circlecircumference 1
#spherediameter 1
#spherevolume 1
#spheresurface 1
#inrad 3 4 5
#anglecosa 3 4 5
#anglecosb 3 4 5
#anglecosc 3 4 5
# following include redundant TCL one liner procedures for sqrt of sum of squares
# sqrt of sum of squares and diagonal using expr
proc diagonal_1 {aa bb} {[expr { sqrt($aa * $aa + $bb * $bb)}] }
# Usage diagonal 1 1 returns 1.4142135623730951
# diagonal using math ops
proc diagonal_2 {aa bb} {[sqrt [+ [* $aa $aa] [* $bb $bb] ] ]}
# Usage diagonal_2 1 1 returns 1.4142135623730951
# diagonal using math hypot function
proc diagonal_3{aa bb} {[ hypot $aa $bb ]}
# Usage diagonal_3 1 1 returns 1.4142135623730951
# time one liners, but sticking >> [ time { set qq [ diagonal_1 1 1 ] } ]
proc diagonal_1x {aa bb} { [ time [sqrt [+ [* $aa $aa] [* $bb $bb] ] ]]} # Sample of TCL One Liner Procedures V2
# written on Windows 10 on TCL 8.6
# working under TCL version 8.6
# gold on TCL Club , 9/20/2020
# Ref. WIKI BOOKS, Tcl_Programming_Introduction pdf
# Book Section contrasts one liners procedures
# versus traditional procedural approach.
# Below contains redundant One Liner procedures
# to contrast alternate techniques and constructs
# start modifications
package require Tcl 8.6
package require math::numtheory
package require math::constants
package require math::trig
package require math
namespace path {::tcl::mathop ::tcl::mathfunc math::numtheory math::trig math::constants }
set tclprecision 17
console show
# following dresses up console output to easy eye
console eval {.console config -bg palegreen}
console eval {.console config -font {fixed 20 bold}}
console eval {wm geometry . 40x20}
puts "Admiral begins operations "
# changes: shifted text, removed empty lines, added easy eye console to deck.
# end modifications
console show
console eval {.console config -bg palegreen}
console eval {.console config -font {fixed 20 bold}}
console eval {wm geometry . 40x20}
namespace path {::tcl::mathop ::tcl::mathfunc}
# contains redundant procs for testing one liner procedures V2
proc pi {} {expr {acos(-1)}}
# proc pi from AMG see below
proc degtoradiansconst {} { expr {180./ [pi] }}
proc degz {} { expr {180./ [pi] }}
proc degx {aa} { expr { degz *acos($aa)}}
proc inrad {a b c} { expr {(sqrt(($a+$b+$c)*($a+$b-$c)*($a-$b+$c)*($b+$c-$a)))/(2.*($a+$b+$c))}}
proc circlediameter {radius} { expr { 2.* $radius }}
proc circlearea {radius} { expr { [pi] *($radius**2)}}
proc circlecircumference {radius} { expr {2.* [pi] *$radius }}
proc spherediameter {radius} { expr { 2.* $radius }}
proc spherevolume {radius} { expr { (4./3.)* [pi] *($radius**3)}}
proc spheresurface {radius} { expr { 4.* [pi] *($radius**3)}}
proc cubevolume {aa} { expr { 1.*$aa*$aa*$aa }}
proc squarearea {aa} { expr { 1.*$aa*$aa }}
proc ellipsoidvolume {aa bb cc} { expr { 1.*(4./3.)* [pi] *$aa*$bb*$cc }}
proc ellipsearea1 { aa bb } { expr { 1.* [pi] *$aa*$bb }}
proc ellipseperimeterx {aa bb} { set tt [ expr { ($aa*$aa+$bb*$bb)/2.}];return [ expr { 2.*[pi]*sqrt($tt)} ] }
proc spherevolumex {aa } { expr { 1.*(4./3.)* [pi] *$aa*$aa*$aa }}
proc spheroidvolumex {aa cc } { expr { 1.*(4./3.)* [pi] *$aa*$aa*$cc }}
proc torusvolumex {aa bb } { expr {(1./4.) * [pi] * [pi] * ($aa + $bb) * ($aa - $bb)*2.}}
proc torussurfacex {aa bb } { expr { [pi] * [pi] * ($aa*$aa - $bb*$bb)}}
proc conesurfacex {aa rr } { expr { [pi] *$rr*$aa}}
proc cylindersurfacesidex {aa rr } { expr {2.* [pi] *$rr*$aa}}
proc cylinderwholesurfacesidex {aa rr } { expr {2.* [pi] *$rr*$aa +2.* [pi] *$rr*$rr}}
proc cylindervolumesidex {aa rr } { expr { [pi] *$rr*$rr*$aa}}
proc conevolumex {aa rr } { expr { (1./3.)* [pi] *$rr*$rr*$aa}}
proc pyramidvolumex {aa bb cc } { expr {(1./3.)*$aa*$bb*$cc }}
proc rectangularprismvolumex {aa bb cc } { expr { $aa*$bb*$cc }}
proc triangularprismvolumex {aa bb cc } { expr { $aa*$bb*$cc*.5 }}
proc polygonperimeterx {aa bb } { expr { $aa*$bb}}
proc rectangleperimeterx {aa bb } { expr {2.*( $aa+$bb)}}
proc parallelogramperimeterx {aa bb } { expr {2.*( $aa+$bb)}}
proc triangleperimeterx {aa bb cc} { expr { $aa+$bb+$cc }}
proc triangletrapezoidx {aa bb cc} { expr { $aa*($bb+$cc)*(1./2.)}}
#law of cosines, aa bb cc are three sides of right triangle, here ordered
#as aa small side , bb middle side, cc largest side.
# inrad is radius of cirle inscribed in right triangle,
# use sides as inrad aa bb cc
proc anglecosa { aa bb cc } { expr {($bb*$bb+$cc*$cc-$aa*$aa)/(2.*$bb*$cc)}}
proc anglecosb { aa bb cc } { expr {($cc*$cc+$aa*$aa-$bb*$bb)/(2.*$aa*$cc)}}
proc anglecosc { aa bb cc } { expr {($aa*$aa+$bb*$bb-$cc*$cc)/(2.*$aa*$bb)}}
#with examples
#for radius of 1
#circlediameter 1
#circlearea 1
#circlecircumference 1
#spherediameter 1
#spherevolume 1
#spheresurface 1
#inrad 3 4 5
#anglecosa 3 4 5
#anglecosb 3 4 5
#anglecosc 3 4 5
# following include redundant TCL one liner procedures for sqrt of sum of squares
# sqrt of sum of squares and diagonal using expr
proc diagonal_1 {aa bb} { expr { sqrt($aa * $aa + $bb * $bb)}}
# Usage diagonal 1 1 s 1.4142135623730951
# maturity value of loan using TCL 8.6 math ops, 10Sep2020
# similar formula for time in days divide years by 360.
# similar formula for interest rate in percent, divide interest by 100.
# should work with any currency and just use consistent units.
# maintain isolating spaces in TCL math ops
proc maturity_value_loan { principal interest years} { [* $principal [+ 1. [* 1. $interest $years ]]] }
# Usage maturity_value_loan 100. .05 1. returns 105.
proc maturity_value_loan_percent { principal percent_i years} { [* $principal [+ 1. [* 1. [/ $percent_i 100.] $years ]]] }
# Usage maturity_value_loan_percent 100. 5. 1. returns 105.
proc maturity_value_loan_days { principal interest days} { [* $principal [+ 1. [* 1. $interest [/ $days 360. ]]]] }
# Usage maturity_value_loan_days 100. .05 360. returns 105.
# following proc session invoke TCLLIB math::trig library
proc pyramid_d {hh bb} { [ acotand [expr (.5*$bb/$hh) ]] }
proc pyra_d {hh bb} { [ acotand [* .5 [/ $bb $hh] ]] }
# Usage pyramid_degrees 57.692 106.346 answer 47.334157521261254
# hh is height of pyramid, units cancel out
# bb is base length of pyramid
# seked = (7 * .5 * 360 cubits) / 250 cubits = 5.04 decimal palms
proc seked_d {hh bb} { [/ [* 7. .5 $bb ] $hh ] }
# usage seked_d 250. 360. equals 5.04
# end TCLLIB
# hbA1c_convert_to_average_blood_glucose mg/dl HbA1c
proc a1c hbA1c { expr { 35.6*$hbA1c -77.3} }
# convert mg/dl to mmol/L average blood glucose
# some papers round off 18.016 to mgdl/18.
proc mgdl_to_mmoll mgdl { expr { $mgdl/18.0 } }
# convert mmol/L to mg/dl average blood glucose
proc mmoll_to_mgdl mmoll { expr { $mmoll*18.0 } }
# *************************************8
# mean_speed_1 is defined as apparent velocity
# of Jupiter along Zodiac in degrees per day
# mean_speed_1 = [ expr { .5 * (velocity_1 - velocity_0 )} ]
proc mean_speed_1 {velocity_1 velocity_0} { expr { .5 * ($velocity_1 - $velocity_0 )} }
# Usage mean_speed_1 1.5 .5 for 1.5 and 0.5 speeds in degrees per day returns 1.
# *******************************
# adding_two_fractions aa/bb + cc/dd =
# ((aa *dd*1.))+(bb*cc*1.))/(bb*dd*1.),
# but must insert 1. factor to return real numbers in TCL math ops
proc adding_two_fractions { aa bb cc dd } { [/ [+ [* $aa $dd 1. ] [* $bb $cc 1. ]] [* $bb $dd 1.] ] }
# suggest maintain spaces in math ops
# Usage adding_two_fractions 1.0 1.0 1.0 1.0 returns 2.0
# Usage adding_two_fractions 1 1 1 1 returns 2.0
# Usage adding_two_fractions 1. 2. 1. 2. returns 1.0
# subtracting_two_fractions aa/bb - cc/dd =
# ((aa *dd*1.))-(bb*cc*1.))/(bb*dd*1.),
# but must insert 1. factor to return real numbers in TCL math ops
proc subtracting_two_fractions { aa bb cc dd } { [/ [- [* $aa $dd 1. ] [* $bb $cc 1. ]] [* $bb $dd 1.] ] }
# subtracting_two_fractions 1. 2. 1. 4. returns 0.25
# subtracting_two_fractions 1. 1. 1. 1. returns 0.0
# subtracting_two_fractions 1 1 1 1 returns 0.0
# multiplying_two_fractions
proc multiplying_two_fractions { aa bb cc dd } { [/ [* $aa $cc 1. ] [* $bb $dd 1. ] ] }
# multiplying_two_fractions 1. 2. 1. 2. returns 0.25
# multiplying_two_fractions 1. 1. 1. 1. returns 1,0
# multiplying_two_fractions 1 1 1 1 returns 1.0
# dividing_two_fractions
# but must insert 1. factor to return real numbers in TCL math ops
proc dividing_two_fractions { aa bb cc dd } { [/ [* $aa $dd 1. ] [* $bb $cc 1. ] ] }
# dividing_two_fractions 1. 1. 1. 2. returns 2.
# dividing_two_fractions 1. 1. 1. 1. returns 1.0
# dividing_two_fractions 1 1 1 1 returns 1.0
# ********************************
proc bodes_law_1 { nn } { return [+ 0.4 [* 0.3 [pow 2 $nn]]] }
# Usage bodes_law_1 1 returns 1.0 Astronomical units for planet Earth
# Usage bodes_law_1 2 returns 0.7 AU for planet Venus
# Usage bodes_law_1 3 returns 1.6 AU for planet Mars
proc bodes_law_2 {} { foreach nn {0 1 2 3 4 5 6 7} { lappend planets [+ 0.4 [* 0.3 [pow 2 $nn]]]};return $planets}
# Usage bodes_law_2 returns list 0.7 1.0 1.6 2.8 5.2 10.0 19.59 38.8
puts " out " # pretty print from autoindent and ased editor
# One Liners Procedures V2
# written on Windows 10 on TCL
# working under TCL version 8.6
# gold on TCL Club , 10Sep2020
package require Tk
package require math::numtheory
package require math::constants
package require math::trig
package require math
namespace path {::tcl::mathop ::tcl::mathfunc math::numtheory math::trig math::constants }
set tclprecision 17
# following dresses up console output to easy eye
console show
console eval {.console config -bg palegreen}
console eval {.console config -font {fixed 20 bold}}
console eval {wm geometry . 40x20}
console eval {wm title . " One Liners Report , screen grab and paste from console 2 to texteditor"}
console eval {. configure -background orange -highlightcolor brown -relief raised -border 30}
# blank table addition
puts "%|table |printed in| tcl wiki format|% "
puts "&| quantity| value| comment, if any|& "
puts "&| testcase number:| |&"
puts "&| value |quantity 1 | |&"
proc pi {} {expr {acos(-1)}}
# proc pi from AMG see below
# ******surface and area calculations ******
proc degtoradiansconst {} { expr {180./ [pi] }}
proc degz {} { expr {180./ [pi] }}
proc degx {aa} { expr { degz *acos($aa)}}
proc inrad {a b c} { expr {(sqrt(($a+$b+$c)*($a+$b-$c)*($a-$b+$c)*($b+$c-$a)))/(2.*($a+$b+$c))}}
proc circlediameter {radius} { expr { 2.* $radius }}
proc circlearea {radius} { expr { [pi] *($radius**2)}}
proc circlecircumference {radius} { expr {2.* [pi] *$radius }}
proc spherediameter {radius} { expr { 2.* $radius }}
proc spherevolume {radius} { expr { (4./3.)* [pi] *($radius**3)}}
proc spheresurface {radius} { expr { 4.* [pi] *($radius**3)}}
proc cubevolume {aa} { expr { 1.*$aa*$aa*$aa }}
proc squarearea {aa} { expr { 1.*$aa*$aa }}
proc ellipsoidvolume {aa bb cc} { expr { 1.*(4./3.)* [pi] *$aa*$bb*$cc }}
proc ellipsearea1 { aa bb } { expr { 1.* [pi] *$aa*$bb }}
proc ellipseperimeterx {aa bb} { set tt [ expr { ($aa*$aa+$bb*$bb)/2.}];return [ expr { 2.*[pi]*sqrt($tt)} ] }
proc spherevolumex {aa } { expr { 1.*(4./3.)* [pi] *$aa*$aa*$aa }}
proc spheroidvolumex {aa cc } { expr { 1.*(4./3.)* [pi] *$aa*$aa*$cc }}
proc torusvolumex {aa bb } { expr {(1./4.) * [pi] * [pi] * ($aa + $bb) * ($aa - $bb)*2.}}
proc torussurfacex {aa bb } { expr { [pi] * [pi] * ($aa*$aa - $bb*$bb)}}
proc conesurfacex {aa rr } { expr { [pi] *$rr*$aa}}
proc cylindersurfacesidex {aa rr } { expr {2.* [pi] *$rr*$aa}}
proc cylinderwholesurfacesidex {aa rr } { expr {2.* [pi] *$rr*$aa +2.* [pi] *$rr*$rr}}
proc cylindervolumesidex {aa rr } { expr { [pi] *$rr*$rr*$aa}}
proc conevolumex {aa rr } { expr { (1./3.)* [pi] *$rr*$rr*$aa}}
proc pyramidvolumex {aa bb cc } { expr {(1./3.)*$aa*$bb*$cc }}
proc rectangularprismvolumex {aa bb cc } { expr { $aa*$bb*$cc }}
proc triangularprismvolumex {aa bb cc } { expr { $aa*$bb*$cc*.5 }}
proc polygonperimeterx {aa bb } { expr { $aa*$bb}}
proc rectangleperimeterx {aa bb } { expr {2.*( $aa+$bb)}}
proc parallelogramperimeterx {aa bb } { expr {2.*( $aa+$bb)}}
proc triangleperimeterx {aa bb cc} { expr { $aa+$bb+$cc }}
proc triangletrapezoidx {aa bb cc} { expr { $aa*($bb+$cc)*(1./2.)}}
# law of cosines, aa bb cc are three sides of right triangle, here ordered
# as aa small side , bb middle side, cc largest side.
# inrad is radius of cirle inscribed in right triangle,
# use sides as inrad aa bb cc
proc anglecosa { aa bb cc } { expr {($bb*$bb+$cc*$cc-$aa*$aa)/(2.*$bb*$cc)}}
proc anglecosb { aa bb cc } { expr {($cc*$cc+$aa*$aa-$bb*$bb)/(2.*$aa*$cc)}}
proc anglecosc { aa bb cc } { expr {($aa*$aa+$bb*$bb-$cc*$cc)/(2.*$aa*$bb)}}
# with examples
# for radius of 1
# circlediameter 1
# circlearea 1
# circlecircumference 1
# spherediameter 1
# spherevolume 1
# spheresurface 1
# inrad 3 4 5
# anglecosa 3 4 5
# anglecosb 3 4 5
# anglecosc 3 4 5
# following include redundant TCL one liner procedures for sqrt of sum of squares
# sqrt of sum of squares and diagonal using expr
proc diagonal_1 {aa bb} { expr { sqrt($aa * $aa + $bb * $bb)}}
# Usage diagonal 1 1 s 1.4142135623730951
# ***** simple interest section *******
# maturity value of loan using TCL 8.6 math ops, 10Sep2020
# similar formula for time in days divide years by 360.
# similar formula for interest rate in percent, divide interest by 100.
# should work with any currency and just use consistent units.
# maintain isolating spaces in TCL math ops
proc maturity_value_loan { principal interest years} { [* $principal [+ 1. [* 1. $interest $years ]]] }
# Usage maturity_value_loan 100. .05 1. returns 105.
proc maturity_value_loan_percent { principal percent_i years} { [* $principal [+ 1. [* 1. [/ $percent_i 100.] $years ]]] }
# Usage maturity_value_loan_percent 100. 5. 1. returns 105.
proc maturity_value_loan_days { principal interest days} { [* $principal [+ 1. [* 1. $interest [/ $days 360. ]]]] }
# Usage maturity_value_loan_days 100. .05 360. returns 105.
# ****** relative error in percent *****************************************
# error in percent is < attested value> over <calculated value> times 100. percent.
# for relative error without percent,
# < attested value> over <calculated value> times 1.0
# for relative error without percent, swap factor 100.0 to 1.0
proc percent_errorx {aa bb} { expr { $aa > $bb ? (($aa*1.)/$bb -1.)*100. : (($bb*1.)/$aa -1.)*100.}}
# Effectively percent_errorx is returning an absolute value of error in percent
# Usage percent_errorx 1.2 1.0 returns 19.99 percent
# Usage percent_errorx 1.0 1.2 returns 19.99 percent
# Usage percent_errorx 1.5 1.0 returns 50.0 percent
proc error_relative {aa bb} { expr { $aa > $bb ? (($aa*1.)/$bb -1.)*1. : (($bb*1.)/$aa -1.)*1.}}
proc error_relative {aa bb} { expr { $aa > $bb ? (($aa*1.)/$bb -1.)*1. : (($bb*1.)/$aa -1.)*1.}}
# Usage error_relative 1.2 1.0 returns 0.199
# Usage error_relative 1.0 1.2 returns 0.199
# Usage error_relative 1.5 1.0 returns 0.50
puts " out "Recent results have indicated that there are bounds and limits on the Collatz_Sequences that might be useful in TCL expressions.Motta, Oliveira, and Cataban reported that the growth between successive odds is 3/4 . Hence, the reasonable expectation or guess that the sequence will reduce in time. A rigorous result from Krasikov and Lagarias was that the number of N's that inside the region 1 to N that will coalesce or reduce to 1 is greater than expr { $N**.84} . Wulf Rehder reported that the bound on the Collatz_Sequences return to the original entry integer was a constant. The Rehder_limit_collatz_sequences constant is expr { (log(3)/log(2))/(log(3)/log(2)+1.)} returns 0.61314719276545848 or 61.3 percent. The complement or < 1 - Rehder_limit> is 0.3868528072345415 or 38.6 percent . Meaning for long Collatz_Sequences and N>20 is that if one is at the Rehder_limit or return boundary of a long Collatz_Sequence, one can estimate the length of remaining steps of the tail. The Collatz_Sequence has 38.6 percent of tail left. It is curious that some of the TCLLIB Gauss_Legendre estimates for numbers of primes less than N are hovering over the lengths or step numbers of some Collatz_Sequences, N<50. Maybe numerical coincidence, but possibly these Gauss_Legendre procs could be hacked into predicting the length of some Collatz_Sequences. These results are not complete mathematical proofs of the Collatz Conjecture, but believe that the bounds will help characterize the envelope or trajectory of the longer Collatz_Sequences.
Lopsy posted that a number n has rough approximate ~log(n) Collatz steps to reach 1. Some Collatz_Sequences with 2 or more downward sequences and multiple breakpoints may be outliers to this ~log(n) formula. Solution for consecutive numbers with same Collatz length of steps starting at n, X = expr { log(n)* ( log(n))* ( log(log(n)))}, if consecutive numbers are present at number n. Have to check out ~log(n) Collatz steps. There are 7 steps for integer 10 whereasas numberPrimesLegendre 10 returns 7.677. There are 23 steps for integer 100 whereas numberPrimesLegendre 100 returns 27.73.
The Collatz_Sequence for 10 is < 10 5 16 8 4 2 1 > with 7 elements. By inspection, the Collatz_Sequence returns or drops below 10 between elements 3 and 4 or numbers 16 and 8 in the sequence. The Rehder_limit estimates the break point as expr { 7. * .613 } returns 4.291 , rounds to 4. The approximate number of terms or computer steps is 7. Using the Rehder_limit, Rehder_complement, and the expected tail of < 16 8 4 2 1 > , the approximate number of elements is estimated as expr { ( 4.* .613 ) / .386 } returns 6.352, a little off. The Collatz_Sequence for 27 has 112 elements. Sequence for 27 has two breakpoints on elements 96 and 104. At 96, breaks between 46 and 23. The Rehder_limit estimates the break point as expr { 112. * .613 } returns 68.656 , rounds to 69. llength sequence_27_breakpoint returns 96. Sequence for 27 has 16 elements in tail.
| Index | Plato’s Cave Analogy | Binary/Decimal Perception | AI Cognition (Probabilistic/Binary) | Human Cognition (Decimal/Deterministic) | Tcl Snippet ... | Analogy Inversion | Quibble |
|---|---|---|---|---|---|---|---|
| 1 | Shadows on wall | Decimal = shadow projection | Sees true bit‑pattern; n = binary string | Sees decimal magnitude; structure hidden | set bits format %b $n | Decimal “size” ≠ structural complexity | Cave metaphor is symbolic, not literal |
| 2 | Prisoners misread shadows | Decimal hides 2‑adic depth | AI reads v2(n) instantly | Humans compute v2(n) manually | regexp -all {0$} $bits | High v2 = low “energy” (flip) | v2 not intuitive in base‑10 |
| 3 | Escape from cave | Binary = outside light | AI sees Collatz as automaton | Humans see chaotic jumps | set n expr {$n%2?3*$n+1:$n/2} | Odd-step may shrink after halving | Automaton view oversimplifies |
| 4 | Forms vs shadows | Binary = form; decimal = shadow | AI models entropy via bit‑length | Humans track decimal growth | set H string length $bits | Entropy deterministic here | Entropy is proxy only |
| 5 | Painful adjustment to light | Switching bases is hard | AI native in base‑2 | Humans culturally base‑10 | set lane expr {$n%8} | Mod‑8 lanes fuzzy | Base choice arbitrary |
| 6 | Sun = truth | Binary structure = “sun” | AI sees spectral ladder k | Humans memorize odd/even steps | set eig expr {pow(0.75,$k)} | Small eig = fast ruin (flip) | k not tunable |
| 7 | Returning to cave | Hard to explain new view | AI outputs binary insights | Humans distrust non‑decimal framing | puts "n=$n bits=$bits" | Binary clarity ≠ human intuition | Communication gap, not error |
| 8 | Cave wall = limited viewpoint | Decimal restricts perception | AI sees Markov‑like drift | Humans expect deterministic proof | set dH expr {$H2-$H1} | Drift undefined in deterministic map | Drift metaphor incomplete |
| 9 | Shadows distort proportions | Decimal exaggerates jumps | AI sees smooth bit‑length drift | Humans see wild spikes | set L string length $bits | Big decimal jump ≠ big binary jump | Decimal scale misleading |
| 10 | Objects casting shadows | Binary operations cast decimal shadows | AI sees right‑shift vs left‑shift | Humans see divide vs multiply | set n expr {$n>>1} | Shift ≠ divide for negatives | Mapping breaks for signed ints |
| Index | Entropy Drift Concept | Gambler Bankroll Analogy | Tcl Snippet ... | Analogy Inversion | Quibble |
|---|---|---|---|---|---|
| 1 | Bit-length H(n) | Bankroll size B | set H [string length [format %b $n] | Big n can drop fast; bankroll rarely does | H is proxy, not entropy |
| 2 | ΔH per step | Gain/loss per round | set dH expr {$H2-$H1} | ΔH deterministic; bankroll stochastic | Drift not probabilistic |
| 3 | Odd-step expansion | Winning streak | if {$n%2} {set n expr {3*$n+1}} | Win streaks raise B; odd steps may shrink after halving | Injection overstated |
| 4 | Even-step compression | Loss event | set n expr {$n/2} | Loss shrinks B; halving exact | Loss ≠ deterministic |
| 5 | Expected drift | Expected bankroll change | set drift expr {$p*$gain + (1-$p)*$loss} | Collatz has no p; gambler does | Drift undefined in deterministic map |
| 6 | Entropy well near 1 | Ruin attractor | while {$n>1} {...} | Ruin = 0; Collatz = 1 | Attractor mismatch |
| 7 | High k → low eig | High volatility → fast ruin | set eig expr {pow(0.75,$k)} | In QM small eig = slow decay | Direction flips |
| 8 | Swarm entropy | Ensemble bankroll | foreach n $list {...} | No interference; bankroll has variance | Classical ensemble only |
| 9 | Entropy collapse | Ruin event | if {$n==1} {...} | Collapse irreversible; bankroll can restart | Collapse metaphor weak |
| 10 | Entropy plateau | Long survival | while {$n>$peak} {...} | Plateau ≠ high bankroll | Plateau from arithmetic, not drift |
| Index | Concept | Tcl Snippet Template ... | Purpose / Use | Analogy Inversion | Quibble |
|---|---|---|---|---|---|
| 1 | Collatz step | set n expr {$n%2?3*$n+1:$n/2} | Core update rule | Odd-step “energy injection” not monotone | Deterministic, not stochastic |
| 2 | Collatz loop | while {$n>1} {set n ...} | Full trajectory | Long plateau ≠ high eigenvalue | No proof of termination |
| 3 | Odd-step count k | if {$n%2} {incr k} | Spectral ladder index | k fixed by n, not tunable | k is heuristic classifier |
| 4 | Eigenvalue ladder | set eig expr {pow(0.75,$k)} | Approx spectral decay | Small eig = fast ruin (flip) | Not physical eigenvalue |
| 5 | Gambler bankroll | set bank expr {$bank*$factor} | Win/loss simulation | Factor ≠ true Collatz growth | Bankroll metaphor breaks |
| 6 | Ruin condition | while {$bank>0} {...} | Absorbing boundary | Ruin ≠ reaching 1 | Mapping is loose |
| 7 | Entropy proxy | set H [string length [format %b $n] | Bit-length entropy | Deterministic map has no true entropy | Proxy only |
| 8 | Mod-8 lane | set lane expr {$n%8} | Swarm pre-filter | Lanes fuzzy, not exact | Classifier, not theorem |
| 9 | Predecessor tree | lappend pred expr {($n-1)/3} | Inverse graph | Many branches → not unitary | Inverse not always valid |
| 10 | Spectral sweep | for {set k 0} {$k<50} {incr k} {...} | Scan eigenvalue bands | k not free parameter | Visualization only |
| Index | Collatz Feature | Quantum Analogy | Gambler Analogy | p-adic Interpretation | Entropy View | Tcl Snippet ... | Analogy Inversion | Quibble |
|---|---|---|---|---|---|---|---|---|
| 1 | Even step n/2 | Energy release; decay | Loss event; bankroll shrinks | v2(n) increases by 1 | Entropy drops (bit-length ↓) | set n expr {$n/2} | QM emission probabilistic; halving deterministic | Entropy proxy only |
| 2 | Odd step 3n+1 | Energy injection | Win event; bankroll jumps | v2 resets after odd | Entropy rises (bit-length ↑) | set n expr {3*$n+1} | Odd-step may shrink after halving | “Injection” overstated |
| 3 | Odd-step count k | Eigenvalue ladder (3/4)^k | Volatility index | Depth of 2-adic descent | Net entropy drift | set eig expr {pow(0.75,$k)} | Small eig = fast ruin (flip) | k fixed by n |
| 4 | Trajectory plateau | Metastable excited state | Long survival before ruin | Low v2 region | Temporary entropy stall | while {$n>$peak} {...} | Plateau ≠ high eigenvalue | Plateau from arithmetic |
| 5 | Descent to 1 | Ground state | Ruin absorbing state | v2 → ∞ in limit | Entropy collapse | while {$n>1} {...} | Ruin=0; Collatz=1 | Collapse metaphor weak |
| 6 | Swarm structure | Spectral bands | Player clusters | p-adic residue classes | Entropy wells | set lane expr {$n%8} | Bands fuzzy, not sharp | Classifier, not theorem |
| 7 | Inverse graph | Quantum superposition | Many possible bankroll paths | p-adic tree | Ensemble entropy | lappend pred ... | No interference in classical Collatz | Superposition metaphor only |
| 8 | Stopping time | Measurement collapse | Final bankroll count | v2(n_final) fixed | Final entropy state | if {$t>=$tmin && $t<=$tmax} {...} | QM collapse irreversible; Tcl window arbitrary | Useful but not physical |
| 9 | Growth spikes | Resonance peaks | Lucky streaks | Low p-adic valuation | Entropy surge | puts $n | Decimal spikes ≠ binary spikes | Decimal scale misleading |
| 10 | Mod-8 lanes | Quantum channels | Betting lanes | p-adic congruence | Entropy funnels | set lane expr {$n%8} | Lanes not invariant | Heuristic only |
| Index | Macro Purpose | Tcl Snippet Macro ... | Notes / Use Case | Analogy Inversion | Quibble |
|---|---|---|---|---|---|
| 1 | Collatz step macro | proc Cstep n {expr {$n%2?3*$n+1:$n/2}} | Core update rule | Odd-step may shrink after halving | Deterministic, not stochastic |
| 2 | Full Collatz loop | proc Cloop n {while {$n>1} {set n Cstep $n}} | Generate trajectory | Long plateau ≠ high energy | No proof of termination |
| 3 | Odd-step counter | proc Codd n {set k 0; while {$n>1} {if {$n%2} {incr k}; set n Cstep $n}; return $k} | Spectral ladder index k | k fixed by n | k is heuristic |
| 4 | Eigenvalue ladder | proc Ceig k {expr {pow(0.75,$k)}} | Approx spectral decay | Small eig = fast ruin (flip) | Not physical eigenvalue |
| 5 | Bit-length entropy | proc H n {string length format %b $n} | Entropy proxy | Deterministic map has no true entropy | Proxy only |
| 6 | Entropy drift | proc dH {n1 n2} {expr {H $n2-H $n1}} | Track bit-length change | Drift undefined in deterministic map | Metaphor only |
| 7 | Gambler bankroll step | proc Gstep {bank factor} {expr {$bank*$factor}} | Win/loss simulation | Factor ≠ true Collatz growth | Bankroll metaphor breaks |
| 8 | Gambler ruin loop | proc Gruin bank {while {$bank>0} {set bank Gstep $bank $f}} | Absorbing boundary | Ruin=0; Collatz=1 | Attractor mismatch |
| 9 | Mod-8 lane classifier | proc lane n {expr {$n%8}} | Swarm pre-filter | Lanes fuzzy, not invariant | Classifier, not theorem |
| 10 | p-adic valuation v2(n) | proc v2 n {regexp -all {0$} format %b $n} | Count trailing zeros | High v2 = low “energy” (flip) | p-adic intuition non-intuitive |
| 11 | Predecessor finder | proc pred n {expr {($n-1)/3}} | Inverse graph | Not all preds valid | Inverse not injective |
| 12 | Spectral sweep | proc sweep {} {for {set k 0} {$k<50} {incr k} {puts Ceig $k}} | Scan eigenvalue bands | k not tunable | Visualization only |
| 13 | Plateau detector | proc plateau n {set peak 0; while {$n>$peak} {set peak $n; set n Cstep $n}} | Detect metastable region | Plateau ≠ high eigenvalue | Arithmetic, not spectral |
| 14 | Entropy well finder | proc well n {set H0 H $n; while {$n>1} {set n Cstep $n; if {H $n<$H0} {return $n}}} | First entropy drop | Entropy deterministic | Proxy only |
| 15 | Multi-domain macro | proc Cinfo n {list n $n bits format %b $n k Codd $n eig Ceig [Codd $n] lane [lane $n} | One-shot summary | Mixing metaphors | Convenience macro |
# These statements should be pastable into the easy eye console.
# ***** simple interest problems in TCL one liners procedures *****
# find simple interest amount from 3 entries as < principal interest years >
proc simple_interest_amount { principal interest years } { expr { ($principal*1.)*(1.+$years*$interest )}}
# Usage simple_interest_amount 5000. .05 7. returns 6750.0
# find simple interest principal from 3 entries as < amount interest years >
proc simple_interest_principal { amount interest years } { expr { ($amount*1.)/(1.+$years*$interest )}}
# Usage simple_interest_principal 6750.0 .05 7. returns 5000.0
# find simple interest rate from 3 entries as < amount principal years >
proc simple_interest_rate { amount principal years } { expr { ((($amount*1.)/$principal)-1.)/$years }}
# Usage simple_interest_rate 6750.0 5000. 7. returns 0.05
# find years of simple interest from 3 entries as < amount principal interest >
proc simple_interest_years { amount principal interest } { expr { ((($amount*1.)/$principal)-1.)/$interest }}
# Usage simple_interest_years 6750.0 5000. .05 returns 7.0
# ****** compound interest problems in TCL one liners procedures ******
# find compound interest amount from 4 entries as < principal interest years compounding_times_per_year >
# cd is compounding times per year, usually 4 quarters or 12 months
proc compound_interest_amount { principal interest years cd } { expr { ($principal*1.)*((1.+( $interest /$cd))**($years*$cd))}}
# Usage compound_interest_amount 5000 .05 7 12 retuRns 7090.180
# find compound interest principal from 4 entries as < amount interest years cd >
# cd is compounding times per year, usually 4 quarters or 12 months
proc compound_interest_principal { amount interest years cd } { expr { $amount*( 1. +(($interest*1.)/$cd ) )**(-1.*$cd*$years)}}
# Usage compound_interest_principal 7090.180 0.05 7 12 returns 4999.997, rounds to 5000.
# find interest in compound interest from 4 entries as < amount principal years cd >
# cd is compounding times per year, usually 4 quarters or 12 months
proc compound_interest_interest { amount principal years cd } { expr { $cd*((($amount*1.0)/$principal)**(1./($cd*$years))-1.)}}
# Usage compound_interest_interest 7090.180 5000. 7 12 returns 0.049, rounds to 0.05
# find years of compound interest from 4 entries as < amount principal interest cd>
proc compound_interest_years { amount principal interest cd } { expr { (log10 (($amount*1.0)/$principal)) / ($cd*log10(1.+(($interest*1.)/$cd) ) ) }}
# Usage compound_interest_years 7090.180 5000. 0.05 12 returns 6.99, rounds to 7 years
# ******** continuous_compounding ******* based on exponential formulas and natural log.
proc amount_continuous_compounding { principal interest years } { expr { $principal* exp ( $interest*$years*1. ) }}
# Usage amount_continuous_compounding 5000. 0.05 7 returns 7095.3377
proc principal_continuous_compounding { amount interest years } { expr { $amount * exp ( $interest*$years* -1. ) }}
#Usage principal_continuous_compounding 7095.33 0.05 7. returns 4999.994, rounds to 5000.
proc interest_continuous_compounding { amount principal years } { expr { (log ( ($amount*1.) /$principal )) / ($years * log (exp(1.) ) ) }}
# Usage interest_continuous_compounding 7095.33 5000. 7 returns 0.04999, rounds to 0.05
proc years_continuous_compounding { amount principal interest } { expr { (log ( ($amount*1.) /$principal )) / ($interest * log (exp(1.) ) ) }}
# Usage years_continuous_compounding 7095.33 5000. 0.05 returns 6.999, rounds to 7 yearsThere is a gold mine of One Liners Programs and content in the Tool Control language TCL 8.6 core distribution, TCL manual pages, and TCLLIB library that can be adapted or recast into brief one liners programs. These one liners programs or procedures can be pasted into the TCL 8.6 console window for quick results, reference the TCL Wiki. Some one liners programs use the return statement, return $value, or return 1 to return the results to the program line. Although many TCL programmers just rely on the last computation being returned by the one liner procedure in the TCL console window. There is some room in the Wiki publications for programming style differences. But it is usually best to put usage, credits, or TCL documentation references for the one liners procedures on separate comment lines. The random procedures make use of the random function and do not return the same answer every time. Dependence on math operator notation, helper procedures, math check examples, and special library functions should be noted in the comment lines.
There are pros and cons to one liner programs in TCL. One may contrast the approach to one liners programs in problem solving versus the traditional procedural approach. There are better routines and methods in faster language constructs in the current TCL core distribution and TCLLIB. Working with recursion, primes, text search, and timing the procedures will quickly show the warts on the one liners programs. To gain speed and shorter computation times, one will generally have to access the TCL core distribution and TCLLIB. Since the TCL interpreter collapses the carriage returns, skips, blank lines, and dead space of traditional written procedures into a single line of machine code, is not every script a one liner program to the parser? As grandfather remarked, the gourmet omelet, beef mulligan stew, and farm buttermilk all go to the same place.
WIKI BOOKS, Programming_Examples pdf WIKI BOOKS, Tcl_Programming_Introduction pdf license https://creativecommons.org/licenses/by-sa/3.0/legalcode creativecommons.org/licenses/by-sa/3.0/ en.wikibooks.org/wiki/Tcl_Programming_Introduction Sample Math Programs, item 2, RS TCLLIB math::mean is quicker by a third over some homebrew code. Additional math functions https://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix-That-is-what-is-your-favorite-one-liner-command-that-handles-a-task-usually-delegated-to-a-much-more-verbose-program-written-in-a-high-level-language http://www.codecodex.com/wiki SOURCE CODE SEARCH ENGINES, INCLUDE TCL???? Google Code Search Koders Krugle Google Code Search Koders Krugle Protecode REFERENCES http://www.codecodex.com/wiki https://www.openhub.net/p?ref=homepage&query=tcl https://en.wikipedia.org/wiki/Portal:Computer_programming https://en.wikipedia.org/wiki/Portal:Free_and_open-source_software https://en.wikipedia.org/wiki/Protecode https://en.wikipedia.org/wiki/List_of_search_engines#Source_code https://blog.robertelder.org/don-libes-expect-unix-automation-tool/
Question from member AV in Russia. So small basic interpreter... Who used small basic interpreters?
A. ## The original tiny basic was distributed in assembler code for the Altair and the 8080 circuit board. Essentially, tiny_basic is a historic legacy of mankind. The original Altair BASIC was about 150 dollars each. Some USA programmers in the 1970s gave away tiny_basic free to break the monopoly. tiny_basic was the first freeware or free software package widely given to the masses (circa 1970). In Russian terms, tiny_basic is the Battleship_Potemkin of computer geeks.
$$$$ The analogy of using tiny_basic to control the large TCL language is like sticking an Apple computer for the human operator in front of a Cray computer. The human mind probably can only understand and use a limited set of instructions, an interface in hardware or TCL? language as a limited set of instructions might be useful. After all, the human mind was designed to chase rabbits.
$$ mostly as a retiree, i am trying to freshen up tcl content on the tcl wiki, adding screenshoots and what meager code i can gin up. I have my limitations, but I am learning.
# conventional expr math operation
# factor 1. forces expression to floating point
proc commission { commission sales } {expr {1.* $commission * $sales}}
# Usage commission .10 100. returns 10.0
# Using math operations notation for speed
proc commission_2 { commission sales } {* 1. $commission $sales }
# Usage commission_2 .1 100 returns 10.0
# *******************************
# commission_rate = commission over sales
set commission_rate {expr {1.*$commission / $sales}}
# conventional expr math operation
proc commission_rate { commission sales } {expr {1.* $commission / $sales}}
# using math operations notation
proc commission_rate_2 { commission sales } [/ [* 1. $commission ] $sales ]
proc commission_rate_2 100. 10.
proc commission_sales_2 { commission sales } {expr {1.* $commission *$sales}} ;# for starting the adventure to infinity and beyond.
;# Titius-Bode set < Earth = 1 ... > as number assignment scheme for planets
;# The Asteriod Ceres is included on most number assignment schemes
;# Ceres represents the Asteriod belt between Mars and Jupiter.
;# The dwarf planet Pluto is included on most number assignment schemes.
proc titius_bode_law_1772 {aa } {expr { (4. + 3 * 2**$aa)*.1 } } ;# ;# $nn=l for Earth,2,...
;# Other planet number schemes are for power laws are available here, < Mercury = 1 ...>
;# from Gaussin (1880) and Armellini (1921)
proc gaussin_formula_1880 {nn} {expr {0.2099 * (1.7226 ** $nn)} } ;# $nn=l for Mercury,2,...9
proc armellini_formula_1921 {nn} {expr {0.283 * (1.53 ** $nn)} } ;# $nn=l for Mercury,2,...11
;# very interesting, Nicolini transformed planet number scheme in Titius_Bode
;# to < Mercury = 1 ...>, refer to Nicolini
proc nicolini_formula_1957 {nn} {expr {0.4 + 0.075 * (2. ** $nn)} } ;# $nn=l for Mercury,2,...
proc basano_hughes_formula_1979 {nn} {expr {0.285 * (1.523 ** $nn)} } ;# $nn=l for Mercury, 2,...
;# Sven-Ingmar Ragnarsson, 1994, modeled Jupiter and the outer planets to Uranus, separately.
;# See the Ragnarsson paper, setting these planet assignment numbers is tricky.
;# $nn=0 for Jupiter, 2 = Saturn, 3 = Uranus ....
proc ragnarsson_formula_1979 {nn} {expr {5.203*(((5./2.)**(2./3.))**$nn) )} } ;# $nn=0 for Jupiter, 2 = Saturn,...
proc list_integers { aa bb} { for {set i 1} {$i<=$bb} {incr i} {lappend boo [* 1. $i ] [* $i 1.]};return $boo}
;# usage, list_integers 1 10
;# set answer_list_integers = [list 1.0 1.0 2.0 2.0 3.0 3.0 4.0 4.0 5.0 5.0 6.0 6.0 7.0 7.0 8.0 8.0 9.0 9.0 10.0 10.0 ]
proc list_titius_bode { aa bb} { for {set i 1} {$i<=$bb} {incr i} {lappend boo [* 1. $i ] [expr { (4. + 3. * 2**$i)*.1}]};if {$i > $bb} {return $boo}}
;# Usage list_titius_bode 1 6
;# set answer [ list 1.0 1.0 2.0 1.6 3.0 2.8 4.0 5.2 5.0 10.0 6.0 19.6]
proc list_gaussin_formula { aa bb} { for {set ii 1} {$ii<=$bb} {incr ii} {lappend boo [* 1. $ii ] [expr {0.2099 * (1.7226 ** $ii)} ]};if {$ii > $bb} {return $boo}}
;# Usage list_gaussin_formula 1 6
;# set answer_gaussin [ list 1.0 0.36 2.0 0.62 3.0 1.07 4.0 1.84 5.0 3.18 6.0 5.48 ]
proc list_armellini_formula { aa bb} { for {set ii 1} {$ii<=$bb} {incr ii} {lappend boo [* 1. $ii ] [expr {0.283 * (1.53 ** $ii)}]};if {$ii > $bb} {return $boo}}
;# Usage list_armellini_formula 1 7
;# set answer_armellini [ 1.0 0.43 2.0 0.66 3.0 1.013 4.0 1.55 5.0 2.37 6.0 3.63 7.0 5.55 ]
Console wrapper for solution proc *************************** ***************************
| table 2 | printed in tcl wiki format | ||
|---|---|---|---|
| quantity | value | value | comment, if any |
| 2: | testcase_number | ||
| 13.67 : | initial length | ||
| 1.0 : | iteration : | ||
| 1.0 : | option switch mode, usually 1 , modes = 2, 3, 4: | ||
| 1.0 : | optional constant, nominal 1 :: | ||
| 1. : | experimental decay constant_K1 : | ||
| Note : | experimental constant_k1 not used : | ||
| 54.679999999999993 : | Koch snowflake perimeter from iteration N : | ||
| 80.916607288626935 : | area initial triangle : | ||
| 107.88880971816924 : | area first iteration : | ||
| 107.88880971816926 : | Koch snowflake area from iteration N : | ||
| 129.4665716618031 : | limit to Koch snowflake area from infinite series : | ||
| table 3 | printed in tcl wiki format | ||
| quantity | value | value | comment, if any |
| 3: | testcase_number | ||
| 4.5566666659999999 : | initial length | ||
| 2.0 : | iteration : | ||
| 1.0 : | option switch mode, usually 1 , modes = 2, 3, 4: | ||
| 1.0 : | optional constant, nominal 1 :: | ||
| 1. : | experimental decay constant_K1 : | ||
| Note : | experimental constant_k1 not used : | ||
| 24.302222218666664 : | Koch snowflake perimeter from iteration N : | ||
| 8.9907341405499785 : | area initial triangle : | ||
| 11.987645520733304 : | area first iteration : | ||
| 13.319606134148117 : | Koch snowflake area from iteration N : | ||
| 14.385174624879966 : | limit to Koch snowflake area from infinite series : | ||
| table 4 | printed in tcl wiki format | ||
| quantity | value | value | comment, if any |
| 4: | testcase_number | ||
| 1.5188888 : | initial length | ||
| 3.0 : | iteration : | ||
| 3.0 : | option switch mode, usually 1 , modes = 2, 3, 4: | ||
| 1.0 : | optional constant, nominal 1 :: | ||
| 1. : | experimental decay constant_K1 : | ||
| Note : | experimental constant_k1 not used : | ||
| 10.80098702222222 : | Koch snowflake perimeter from iteration N : | ||
| 0.99897034342930124 : | area initial triangle : | ||
| 1.3319604579057349 : | area first iteration : | ||
| 1.5457318894214702 : | Koch snowflake area from iteration N : | ||
| 1.598352549486882 : | limit to Koch snowflake area from infinite series : | ||
| table 5 | printed in tcl wiki format | ||
| quantity | value | value | comment, if any |
| 5: | testcase_number | ||
| 0.50629629600000003 : | initial length | ||
| 4.0 : | iteration : | ||
| 3.0 : | option switch mode, usually 1 , modes = 2, 3, 4: | ||
| 1.0 : | optional constant, nominal 1 :: | ||
| 1. : | experimental decay constant_K1 : | ||
| Note : | experimental constant_k1 not used : | ||
| 4.8004389546666664 : | Koch snowflake perimeter from iteration N : | ||
| 0.11099671768713089 : | area initial triangle : | ||
| 0.14799562358284118 : | area first iteration : | ||
| 0.17499619688396309 : | Koch snowflake area from iteration N : | ||
| 0.17759474829940941 : | limit to Koch snowflake area from infinite series : | ||
| table 7 | printed in tcl wiki format | ||
| quantity | value | value | comment, if any |
| 7: | testcase_number | ||
| 0.16876543199999999 : | initial length | ||
| 5.0 : | iteration : | ||
| 1.0 : | option switch mode, usually 1 , modes = 2, 3, 4: | ||
| 1.0 : | optional constant, nominal 1 :: | ||
| 1. : | experimental decay constant_K1 : | ||
| Note : | experimental constant_k1 not used : | ||
| 2.1335284242962951 : | Koch snowflake perimeter from iteration N : | ||
| 0.012332968631903429 : | area initial triangle : | ||
| 0.016443958175871239 : | area first iteration : | ||
| 0.019604426284356775 : | Koch snowflake area from iteration N : | ||
| 0.019732749811045485 : | limit to Koch snowflake area from infinite series : |
gold 12/22/2025. Would this be useful as a template? You can tell me different, but I most always start with working template and go coding from that template foundation.
Starting complex TCL code from scratch is not easy for me, and I daresay not easy for AI Models either. You may disagree. Using only built-in Tk icons here (no external files needed, no "image does not exist" errors).These icons (::tk::icons::error, ::tk::icons::warning, ::tk::icons::question, ::tk::icons::information) are standard in Tk 8.5+ and appear automatically when you use tk_messageBox or certain dialogs. Here is a complete, self-contained Tcl/Tk example that reliably adds buttons/icons to the top right of a window. Working code used TCL Active State on Windows 11.
#!/usr/bin/env wish
# Complete example: Top-right buttons with built-in Tk icons
package require Tk
# Working code used TCL Active State on Windows 11.
# Main window
toplevel .editor
wm title .editor "Tcl/Tk Editor - Built-in Icons on Top Right"
wm geometry .editor 800x600
# --- Optional menu bar (left-aligned standard items) ---
menu .editor.menubar
.editor configure -menu .editor.menubar
.editor.menubar add command -label "Copy" -command {event generate .editor.txt <<Copy>>}
.editor.menubar add command -label "Select All" -command {.editor.txt tag add sel 1.0 end}
.editor.menubar add command -label "Exit" -command {exit}
# --- Top toolbar frame (key for reliable right alignment) ---
frame .editor.topbar -relief raised -bd 2 -bg lightgray
pack .editor.topbar -side top -fill x
# Define procedures FIRST (prevents silent callback failures)
proc doInfo {} {
tk_messageBox -message "Info icon clicked!" -icon info
}
proc doQuestion {} {
tk_messageBox -message "Question icon clicked!" -icon question
}
proc doWarning {} {
tk_messageBox -message "Warning icon clicked!" -icon warning
}
proc doError {} {
tk_messageBox -message "Error/close icon clicked!" -icon error
}
proc doExit {} {
destroy .editor
}
# Create buttons using built-in icons
button .editor.topbar.exit -image ::tk::icons::error -command doExit -relief flat
button .editor.topbar.warning -image ::tk::icons::warning -command doWarning -relief flat
button .editor.topbar.question -image ::tk::icons::question -command doQuestion -relief flat
button .editor.topbar.info -image ::tk::icons::information -command doInfo -relief flat
# Pack from RIGHT to LEFT → aligns to top-right
pack .editor.topbar.exit -side right -padx 4 -pady 2
pack .editor.topbar.warning -side right -padx 4 -pady 2
pack .editor.topbar.question -side right -padx 4 -pady 2
pack .editor.topbar.info -side right -padx 8 -pady 2
# Optional: add a text button on the left side of the toolbar
button .editor.topbar.copy -text "Copy" -command {event generate .editor.txt <<Copy>>}
pack .editor.topbar.copy -side left -padx 8 -pady 2
# --- Main text widget ---
text .editor.txt -undo true -wrap word -font {Courier 12}
pack .editor.txt -expand yes -fill both -padx 4 -pady 4
.editor.txt insert end "Sample content:\nc:/Greetings/Bob\nAloha dear friend\n"
focus .editor.txt
# Force layout update
update idletasks
# Initial confirmation that icons loaded correctly
tk_messageBox -message "Window ready! Check the four built-in icons on the top right." -icon info
# 1. Define the proc first
proc doMyNewThing {} {
tk_messageBox -message "My new button works!"
}
# 2. Create the button (use built-in icon or text)
button .editor.topbar.mynew -image ::tk::icons::question -command doMyNewThing -relief flat
# 3. Pack it to the right (furthest right if packed first)
pack .editor.topbar.mynew -side right -padx 4 -pady 2#!/usr/bin/env wish
package require Tk
# Main window
toplevel .editor
wm title .editor "Text Replace Demo"
wm geometry .editor 800x500
# Top toolbar frame
frame .editor.topbar -relief raised -bd 2 -bg lightgray
pack .editor.topbar -side top -fill x
# Procedure for the action
proc ExecuteX {} {
set txt .editor.txt
# Get current line number (where cursor is)
set curLine [lindex [split [$txt index insert] .] 0]
# Get text of current line (the file path)
set pathLine [$txt get $curLine.0 $curLine.end]
set path [string trim $pathLine]
# Get next line (the replacement message)
set nextLineNum [expr {$curLine + 1}]
set message [$txt get $nextLineNum.0 $nextLineNum.end]
set message [string trim $message]
if {$message eq ""} {
tk_messageBox -message "No message on next line!" -icon warning
return
}
if {![file exists $path]} {
tk_messageBox -message "File not found:\n$path" -icon error
return
}
# Read the file
set fh [open $path r]
set content [read $fh]
close $fh
# Replace all "XXX" with the message
set newContent [string map {XXX $message} $content]
# If no change, say so
if {$newContent eq $content} {
tk_messageBox -message "No 'XXX' found in file." -icon info
return
}
# Write back
set fh [open $path w]
puts -nonewline $fh $newContent
close $fh
tk_messageBox -message "Success!\nReplaced XXX with:\n$message\nin file:\n$path" -icon info
}
# Button with built-in icon (question mark = good for "action")
button .editor.topbar.execute -image ::tk::icons::question -command ExecuteX -relief flat
pack .editor.topbar.execute -side right -padx 8 -pady 2
# Optional label or tooltip
.editor.topbar.execute configure -takefocus 0
# Main text widget
text .editor.txt -undo true -wrap word -font {Courier 14}
pack .editor.txt -expand yes -fill both -padx 8 -pady 8
# Insert your example text
.editor.txt insert end "c:/Greetings/Bob\nAloha dear friend\n\n"
.editor.txt insert end "(Place cursor on the path line and click the ? icon to replace XXX in the file)"
# Place cursor on first line for demo
.editor.txt mark set insert 1.0
focus .editor.txt
# Final layout update
update idletasks
tk_messageBox -message "Demo ready!\n\nPlace cursor on first line\nClick the ? icon on top right" -icon infoTaylor series for tangent
;# puts taylor tangent series into pade tangent
;# of rational numbers ratio into horners form
;# num/denum=(1/45*$x**9 - 22*$x**7 + 3003*$x**5 - 105105*$x**3 + 765765*$x)/($x**8 - 308*$x**6 + 21021*$x**4 -
360360*$x**2 + 765765)
;# num=1/45*(((($x**2 - 990)*$x**2 + 135135)*$x**2 - 4729725)*$x**2 + 34459425)*$x
;# denum=((($x**2 - 308)*$x**2 + 21021)*$x**2 - 360360)*$x**2 + 765765
symdiff {(1/45.*$x**9 - 22*$x**7 + 3003*$x**5 - 105105*$x**3 + 765765*$x)} x
((((((9 * pow($x, 8)) * (1 / 45.)) - ((7 * pow($x, 6)) * 22)) + ((5 * pow($x, 4)) * 3003)) - ((3 * pow($x, 2)) * 105105)) + 765765.0)
symdiff {($x**8 - 308*$x**6 + 21021*$x**4 - 360360*$x**2 + 765765)} x
((((8 * pow($x, 7)) - ((6 * pow($x, 5)) * 308)) + ((4 * pow($x, 3)) * 21021)) - ((2 * $x) * 360360))
Section 8 for Math Geeks ---- Sample math problems loaded into search engines. ----- Collecting test problems for future calculator ---- Search engine math >>>> ( (88+98+91+92+91+ 93) / 5.) + 46.7) / 28.7 5.48083624 correct ---- Online conversion of average glucose to A1c: https://professional.diabetes.org/dia... Formula to convert estimated glucose to A1c: A1C(%) = (Estimated average glucose(mg/dL) + 46.7) / 28.7 ---- Sample problem ---- Sum of 5 readings over a day. Search engine math >>>>[88+98+91+92+91+ 93] = 462 correct sum over a day, ---- Search engine math >>>> ( 88+98+91+92+91+ 93 ) / 5 = 92.4 correct sum ---- Search engine math >>>> ( (88+98+91+92+91+ 93) / 5.) + 46.7) / 28.7 ---- 5.48083624 correct ***** Note. This formula uses average BG readings from a home glucometer, not as accurate as lab blood test. But useful as a check on home glucometer results ---- Sample problem 2 ---- Search engine math >>>>( (81+77.4+73.8 +81+73.8)) / 5.) + 46.7) / 28.7 4.32404181 correct ---- Results from 72 hour Sardine Challenge. Subject to interpretation ---- Kickstart Metabolism In 3 Days With Sardines ---- notes. (81+77.4+73.8 +81+73.8)/5= ---- ((((81 + 77.4) + 73.8) + 81) + 73.8) / 5= 77.4 Avg BG ---- 77.4 Avg BG ~ 4.2 = A1C ---- Note. Now that I am impressed, looks like the Sardine Team has cleared up a keto block within 3 days. ---- Note. Additional significant figures are used to check the TCL calculator, not to infer the accuracy of inputs and product reports. Meaning here, round to nearest tenth 0.1. ---- ---- **"rise and fall" of Energy as Suggested by Hexagrams?** ---- Do you recall any of our previous discussions that connect to the "rise and fall" of energy as suggested by Hexagrams? In Chinese literature, it’s often said that maximum hexagram energy occurs at line 5. The question is, I’m not entirely sure how this maximum energy relates to quantum effects. You may see it differently. ---- ** Fits to SSCI function** ---- The Gaussian Model and the Golden Ratio Model charts were developed for SSCI curves. The SSCI models are effectively boundary value problems for non-linear functions. Boundary value problems match the end points and break points of a curve for solution. Meaning the boundary value curves are generated from origin point (line 1), normalized peak or break point (line 4/5), and the final end point (line 6). The curve peak is usually normalized either at 1, 10, 100, or some power of ten. The Golden Ratio Model uses a multiplicative rise by φ ≈1.618 up to line 5 as break point, then uses an explicit fall by dividing by φ at line 6. The sharp fall to normalized height 6.18 at line 6, division by φ, creats the classic rise-fall asymmetry of Elliot waves/golden waves. In the precise Golden Ratio Model we've been using, the orange line rises steadily and exponentially, hits the maximum peak at line 5, and then falls symmetrically down or backward. The blue line or simple Qi energy is a smoother, more linear appearing buildup from the Gaussian function for comparison, with a very gentle softening at line 6. ---- In the hexagram’s six-line structure, Qi energy “rises” as one moves from line 1 (the germ or potential) to line 4 or 5 (the peak of power or manifestation). The hexagram often releases or transforms at line 6, which traditionally signals overextension or transition. If we interpret this through a quantum lens, line 5 could be compared to a state of maximum probability amplitude before a collapse or transition into another quantum state. This interpretation fits with the yin–yang cyclic dynamic. Energy doesn’t vanish at the peak. Energy crosses a boundary, possibly analogous to a quantum tunneling or phase shift into a new configuration. ---- **Background >>> Rise and Fall of Energy Qi in the Each Hexagram** ---- **Introduction to the I Ching Oracle Book** ---- The I Ching Oracle Book is in the form of sixty four situations, states of Energy, or changing conditions that English speaking people call hexagrams. The Hexagrams are called kua in modern Chinese. The sixty-four Hexagrams contain a total of 384 lines in Chinese Western Zhou dialect. Each Hexagram situation or condition contains the six stages of its own change in rise and fall. The Hexagram is in changing Eternal flux as the Hexagram Energy expands, rises to a peak, and returns to its opposite Energy. The Eternal Energy cycle of Hexagrams is simply expressed as Yin becomes Yang and then, Yang becomes Yin. ---- **Rise and Fall of Energy Qi in the Each Individual Hexagram** ---- **6 Steps in Rise and Fall of Energy Qi** ---- in Individual Hexagrams from the I Ching Oracle Book ----
Individual Hexagram Energy is about to come into being. Individual Hexagram Energy is beginning, Individual Hexagram Energy is expanding. Individual Hexagram Energy is approaching maximum potential. Individual Hexagram Energy is peaking. Individual Hexagram Energy is passing its peak and turning toward its opposite condition.
----
*** Subroutine for table in TCL Wiki format
Adapted proc from RS
proc table_format_out n {
set sum 0
# initial level
set count 0.0
set glucose 100.
puts "%| table| | printed in|TCL format |% "
puts "%| homa_IR_2 units | insulin units |glucose units |comment, if any|% "
# adapted proc from <RS>
# printout in TCL WIKI format table
for { set i 1 } { $i <= $n } { incr i } {
set count [+ $count .1]
set insulin $count
set homa_IR_2 [ HOMA_IR2 $insulin $glucose ]
set insulin [ precisionx 3 $insulin ]
set glocose [ precisionx 3 $glucose ]
puts "&| [ precisionx 3 $homa_IR_2 ] | $insulin | $glucose | |&"
incr sum $i
}
return $sum
}
table_format_out 90
=====
----
*** Subroutine for table in TCL Wiki format***
----
Adapted proc from [RS]
---- proc table_format_out n {
set sum 0
# initial level
set count 0.0
set glucose 100.
puts "%| table| | printed in|TCL format |% "
puts "%| homa_IR_2 units | insulin units |glucose units |comment, if any|% "
# adapted proc from <RS>
# printout in TCL WIKI format table
for { set i 1 } { $i <= $n } { incr i } {
set count [+ $count .1]
set insulin $count
set homa_IR_2 [ HOMA_IR2 $insulin $glucose ]
set insulin [ precisionx 3 $insulin ]
set glocose [ precisionx 3 $glucose ]
puts "&| [ precisionx 3 $homa_IR_2 ] | $insulin | $glucose | |&"
incr sum $i
}
return $sum
}
table_format_out 90 =====
gold 2/28/2024 Update. Received constructive feedback from offline and thanks to @ava____. & Under Test
@Ava____ >>> Memoization is a technique used in computer science to improve the efficiency of a program by storing the results of expensive function calls and returning the cached result when the same inputs occur again. This avoids redundant calculations and speeds up the program. To implement memoization in your TCL code, you can create a dictionary (hash table) to store the results. Implement memoization to avoid redundant calculations. For example, you can store the results of procedure calls in variables and reuse them when necessary.
Modify the dice_sides_N procedure to check if the result is already stored in the memoized dictionary. If it is, return the cached result; otherwise, calculate the result and store it in the dictionary:
proc dice_sides_N { dice_sides } {
if {[dict exists $memoized $dice_sides]} {
return [dict get $memoized $dice_sides]
}
set result [expr { 1 + int(rand()*$dice_sides)}]
dict set memoized $dice_sides $result
return $result
}By using memoization, you can reduce the number of expensive calculations performed by your code, resulting in improved efficiency.
proc optimum_N { dice_sides } {
if {[dict exists $memoized $dice_sides]} {
return [dict get $memoized $dice_sides]
}
set result [expr { int(1.718281828 *$dice_sides) }]
dict set memoized $dice_sides $result
return $result
}
Binary numbers look simple on the page, but the language around them can be misleading. People talk about “left shifts” and “right shifts” as if the machine has a sense of direction, but it doesn’t; those words are just our shorthand for how bit positions move when a number is doubled or halved. A binary number is written with the most significant bit on the left and the least significant on the right. Take 13, which appears as 1101: the leftmost 1 stands for 8 and the rightmost 1 stands for 1. If you slide everything one place toward the low‑value end, you get 110, which is 6, and that’s exactly what a right shift does—divide by 2 and drop the last bit. In the Collatz process, every even step is just that operation. A left shift goes the other way: push the bits toward the high‑value end and you’ve doubled the number. Shift 1101 left and you get 11010, which is 26. Hardware treats this as “multiply by 2 and ignore anything that spills off the edge.” ???? The odd step in Collatz, the familiar 3+1, can be unpacked as 2+1.???? The 2 term is the left shift, then you add the original number and bump it by one. After that, Collatz immediately strips off factors of 2 until the number becomes odd again, which in binary is just repeated right shifting until the trailing zeros disappear. Inside the machine, none of this is labeled left or right; the hardware only knows bit positions—0, 1, 2, and so on. The directional language is something humans invented because we draw numbers horizontally, while the machine simply updates indices.
# These are adapted from Brent Walsh's book and N.R. in C.
# Make sure you call randomize first, then you can use the others ...
# random_range 1 8
# use brackets in expr
proc randomize { seed } {
global rand
set rand(IA) 9301
set rand(IC) 49297
set rand(IM) 233280
set rand(seed) $seed
}
proc random { } {
global rand
set rand(seed) [expr { ($rand(seed) * $rand(IA) + $rand(IC)) % $rand(IM)}]
return [expr $rand(seed)/double($rand(IM))]
}
proc random_range { low up } {
set delta [expr { $up - $low}]
set comp [expr { double($low + ([random]*$delta))}]
return $comp
}
randomize 12345678puts " random number expr { int( [ random_range 1 6)} ] "
Here is abbreviation of the 12 rules that define the syntax and semantics of the Tcl language:
1. Command Structure: A Tcl script is composed of one or more commands, separated by semicolons or newlines.
2. Command Evaluation: A command is processed in two steps – first, the Tcl interpreter divides the command into words and performs substitutions. Then, the first word is used to locate a routine to execute the command.
3. Word Separation: Words in a command are separated by white space.
4. Double Quotes: A word enclosed in double quotes allows for command, variable, and backslash substitutions.
5. Argument Expansion: Words starting with "{}" are treated as lists and added to the command being substituted.
6. Braces: Braces enclose a word without any substitutions or special interpretation of characters.
7. Command Substitution: Open brackets initiate command substitution, which replaces the brackets and all characters between them with the result of the script.
8. Variable Substitution: Dollar signs followed by a variable name replace the dollar sign and name with the variable's value.
9. Lists: Lists are sequences of elements separated by white space, with elements being any valid Tcl string.
10. Quoting: Backslashes, braces, and quotes can be used to prevent certain characters from being treated as command separators or substitutions.
11. Control Structures: Tcl provides control structures for conditional execution, loops, and error handling, such as if/else, for, while, and catch.
12. Error Handling: Built-in mechanisms like catch command and error return value help in handling and trapping errors in Tcl scripts.
global theta
set theta 1.3063778838630806904686144926
proc mills_constant_tester {limit} { global theta;
expr { int( [ expr {($theta**(3**$limit))} ] )}}
puts " mills_constant [ mills_constant_tester 1 ] "
puts " mills_constant [ mills_constant_tester 2 ] "
puts " mills_constant [ mills_constant_tester 3 ] "
puts " mills_constant [ mills_constant_tester 4 ] "
# mills_constant 2
# mills_constant 11
# mills_constant 1361
# mills_constant 2521008886
# big numbers evaled and large significant figures in constant, results limited quickly in most setups. Condition that N>10, primes end in either 1,3,5,7 for base 10? In base 10, prime numbers end in either 1, 3, 7, or 9. The last digit of a prime number cannot be 0, 2, 4, 6, or 8 because those numbers are all divisible by 2. The last digit cannot be 5 because that would make the number divisible by 5. This leaves us with the last digits 1, 3, 7, and 9.
gold 2/2/2026. FM Would you and other members be willing to co-author a wiki page on a namespace workaround for typed variables. I can’t speak for others, but a namespace-based starter page on typed variables (your idea) would be educational for me. Proposed name of new Tcl Wiki page =equals= "Simulating Typed Variables with Namespaces." Themes of safe variable handling in scripts and improving reliability in algorithmic code. Page-name signals proposed namespace might be a practical workaround and research for some limited tasks, not considered a replacement for core and not to overpromise a core change here.
Is it possible to adapt the recursion code to a typed “garden”?
namespace eval ::typed {
# Hidden storage for type metadata: varName → type (string, list, int, etc.)
variable types
array set types {}
# Factory / typed setter
# Usage: ::typed::list myvar {a b c}
# ::typed::string greeting "hello"
proc tset {type varName value} {
variable types
uplevel 1 [list set $varName $value]
set types($varName) $type
trace add variable $varName write [list ::typed::enforce $varName $type]
return $value
}
# Enforce on write (basic demo: just warn / prevent bad write)
proc enforce {varName expectedType name1 name2 op} {
variable types
upvar 1 $varName val
if {$types($varName) ne $expectedType} {
error "Type violation: $varName expected $expectedType, got $types($varName)"
}
# Could add more checks (e.g. validate value matches type)
}
# Safe getter that reminds you to use typed access
proc tget {varName} {
uplevel 1 [list set $varName]
}
# Wrapped eq that checks types
proc typed_eq {aVar bVar} {
variable types
upvar 1 $aVar a $bVar b
if {![info exists types($aVar)] || ![info exists types($bVar)]} {
return [string equal $a $b] ;# fallback
}
if {$types($aVar) ne $types($bVar)} {
error "Cannot eq different types: $types($aVar) vs $types($bVar)"
}
return [string equal $a $b]
}
# Wrapped in (very simplistic – only same-type lists for demo)
proc typed_in {elemVar listVar} {
variable types
upvar 1 $elemVar e $listVar lst
if {![info exists types($listVar)] || $types($listVar) ne "list"} {
error "$listVar is not a typed list"
}
# Real check would use lsearch or expr {$e in $lst}, but with type guard
return [expr {$e in $lst}]
}
# Add more wrappers as needed: typed_<, typed_+, typed_pred, etc.
# For mathop-style: alias them inside your recursion ns
}
# Example usage
::typed::tset list mylist {apple banana}
::typed::tset string fruit "apple"
puts [::typed::typed_in fruit mylist] ;# → 1 (ok)
puts [::typed::typed_eq fruit mylist] ;# → error: different types
# Cleanup demo
trace remove variable mylist write [list ::typed::enforce mylist list]
unset ::typed::types(mylist)namespace eval ::typedliner {
namespace path {::tcl::mathop ::tcl::mathfunc ::typed}
# Import or alias typed versions of operators you use most
interp alias {} [namespace current]::= {} ::typed::typed_eq
interp alias {} [namespace current]::in {} ::typed::typed_in
# Add typed_<, typed_+, typed_pred, typed_succ, etc. as needed
# Typed factories for your recursion variables
proc tfunc {name argl body} {
# Could wrap proc creation to auto-type args/result if desired
uplevel 1 [list proc $name $argl $body]
}
# Example: typed versions of your base funcs
::typed::tset int zero 0
::typed::tset int one 1
# Now redefine McCarthy-style helpers using typed ops
tfunc succ {x} {+ [tget x] 1} ;# or use typed_+
tfunc pred {n} {[= [tget n] [tget one]]? [tget zero] : ...} ;# etc.
# Your original func bodies can mostly stay, but swap = → typed_eq, in → typed_in, etc.
}Notes on 19Feb2024. Chinese excavations reveal a possible related divination system with space of 60 combinations. There are current Buddhist temple methods that picking a stick from 64 sticks or some other number. Popular Game of Pick up Sticks in West. In that case, the classic formula would be 1/64 for equal Hexagram probability and the probability space would 64 items. Bernoulli probability formula, P(Yang)= 1- P(Yin)
Notes on 13Feb2024. 4 yes-no binary sticks equals 2**4 combinations or 16 combinations. Probability of single cast 1/(2**4) or 1/16. Space = 16 items 5 yes-no binary sticks equals 2**5 combinations or 32 combinations. Probability of single cast 1/(2**5) or 1/32. Space = 32 items 6 yes-no binary sticks equals 2**6 combinations or 64 combinations. Probability of single cast 1/(2**6) or 1/64. Space = 64 items 7 yes-no binary sticks equals 2**7 combinations or 128 combinations. Probability of single cast 1/(2**7) or 1/128. Space = 128 items The three most frequently occurring characters are: 吉 auspicious 无咎 no misfortune 凶 ominous Thinking in Bullet Points There are a total of 384 lines in the I Ching Oracle Book There are roughly 100 lines with character "mistake", Chinese "Liu" 100/384 = 0.2604 probability of mistake Liu appearing (384-100)= 284 number of lines without mistake Liu appearing 284/384= 0.7396 probability of mistake Liu not appearing The probability of casting a line with the character "mistake" is 0.2604, roughly 1/4 or 0.25 The probability of casting a line with no character "mistake" is 0.7396, roughly 3/4 or 0.75 The probability of casting a line with or without character "mistake" is 0.2604 + 0.7396 = 1 One might conclude the I Ching Oracle Book is rigged not to cast a character "mistake".
| # | Metric | TCL 8.6 | Python 3.14+ | Quibble Notes |
|---|---|---|---|---|
| 1 | Total lines (all content) | 571 | 699 | Python is 22.4 pct longer overall due to docstrings and type annotations |
| 2 | Hash-comment lines (#) | 271 | 168 | TCL tutorial header is 120 lines; Python spreads equivalent text across docstrings |
| 3 | Docstring delimiter lines (""") | n/a | 28 | Python only; one open plus one close per function; no TCL structural equivalent |
| 4 | Blank / whitespace lines | 38 | 86 | PEP 8 requires two blank lines between top-level defs; TCL has no such convention |
| 5 | Executable code lines (derived) | 262 | 417 | Total minus hash-comments minus docstring delimiters minus blanks |
| 6 | Executable lines if docstring body counted as docs | 262 | ~300 | Narrower gap; both languages express same algorithm in similar volume |
| 7 | Comment-to-total ratio | 47.5 pct | 28.0 pct | TCL single-block tutorial inflates this; Python distributes docs differently |
| 8 | Code-to-total ratio | 45.9 pct | 59.7 pct | Python type annotations add one line per typed argument in function signatures |
| 9 | Sub-function calls per top-level measurement | 14 | 14 | Both languages make identical call depth due to same NASA decomposition |
| 10 | Assert helper calls per measurement | 9 | 9 | assertConditionIsTrue fires 9 times per call in both languages |
| 11 | Measured speed -- modular NASA version | ~13.5 us | ~1.35 us | TCL measured; Python measured; CPython bytecode VM is roughly 10x faster here |
| 12 | Measured speed -- equivalent inlined version | ~7.3 us (est) | 0.73 us (measured) | Inlined removes 13 sub-calls; Python measured directly; TCL extrapolated |
| 13 | NASA 25-line rule overhead factor | ~1.84x (est) | 1.84x (measured) | Decomposition costs same proportional penalty in both languages |
| 14 | Approx cost per sub-call (Python measured) | -- | ~44 ns | CPython 3.11+ CALL instruction; TCL proc call is proportionally similar |
| 15 | Bytecode cross-boundary inlining | Not available | Not available | Neither TCL nor CPython inlines across proc/def boundaries; NASA rule prevents it |
| 16 | CPython specializing adaptive interpreter impact | -- | Reduced | PEP 659 specializer works best on hot loops in one function; NASA decomposition scatters hot paths |
PYK 2020-10-13: Hi gold, thank you for the cool pages you've contributed to this wiki. Your recent edit to upvar sugar was reverted by stevel, probably because it was so broad. My opinion: The concern is that if such broad reference sections proliferate, they lose the value they might have had. There is a natural hierarchy to content on the wiki. The page above upvar sugar is probably something like little language. A link to math sugar, for example, is a sibling to upvar sugar, so probably belongs on a higher page, and not on the upvar sugar page. For navigational purposes it's good enough to be able to browse through a "path" of links to some indirectly-related content, and to constrain the "reference" section only to directly-related pages, i.e. pages that might be considered siblings, children, or parents.
PYK 2020-10-21: In my recent edit to Playing Recursion V2 >> demo examples for one liner programs I removed the copyright notice. The entire content of this wiki is intended to be in th public domain, and thus copyright notices on individual pages are unneeded and could cause confusion. See Who owns the content on this Wiki.
gold 2020-10-20. How about me just loading the pix and charts alone at the bottom of these older works by other authors? That should not spoil the looks and "optics" of the older author pages. Since my moniker is on the pix, if readers want more info, refs, and the generating code, they may contact me. I do not have an ax to grind on copyright, other than no liability to me and TCL Wiki. I have some brain fog late at night, page was overwritten somehow. I have reloaded your edit 102 from the history, with omissions per request.
gold 2021-5-8. Removing copyright notices on <gold> authored pages as spare time allows. I do not have an ax to grind on copyright, other than no liability to me and TCL Wiki. The 2007 paper of David McFarland provided an excellent history of the quarter square multiplication algorithm in both the ancient and modern eras. The college institutes, textbooks, and computer companies in the USA that previously used the Babylonian mathematical ideas without credit may be glad to know that the Babylonian copyrights and patents expired about 4000 years ago.
gold 3/28/2024 Update. Received feedback from Maintainer ZXASX.
How destroy a redundant page? Thank you. Gold on Wiki. Shortening some titles and redundant pages, may take a while.
gold 3/28/2024 Thank you for your help on the login. Certainly, I will address your issues as best that I can. I guess that I could work on changes on outside editor, until more ready for publication. My Titles could be more brief. Gold on wiki.
ZXASX >>>> Edit the page and change the content to a single space.
asdfa >>> Recently able to delete a page by replacing its entire contents with a single space then saving it. This was the procedure used for the prior wiki. Is it still the right way to delete a page? Yeah, I know it's poorly documented, but it's what we (seem to) have
gold 3/28/2024: Note to clean up crew. Checking end of line issues here from laptop PC editor. If one sees a syntax error or brace typo error, go ahead and change. My eyes are bad on these tiny fonts. I am deleting some redundant files, now that I know how to close them.
If urgent matter, leave comment out in plain sight, here at bottom of page. As I am more likely to see it. If the issue is resolved, I may sweep under rug later.
APN 2026-09-09 Please restrict your content to that which has direct relevance to Tcl/Tk. Many of your recent posts do not meet that criterion. Thanks for your understanding.
Please include your wiki MONIKER and date in your comment with the same courtesy that I will give you. Thanks, gold 12Dec2018
PYK 2020-10-13: Hi gold, thank you for the cool pages you've contributed to this wiki. Your recent edit to upvar sugar was reverted by stevel, probably because it was so broad. My opinion: The concern is that if such broad reference sections proliferate, they lose the value they might have had. There is a natural hierarchy to content on the wiki. The page above upvar sugar is probably something like little language. A link to math sugar, for example, is a sibling to upvar sugar, so probably belongs on a higher page, and not on the upvar sugar page. For navigational purposes it's good enough to be able to browse through a "path" of links to some indirectly-related content, and to constrain the "reference" section only to directly-related pages, i.e. pages that might be considered siblings, children, or parents.
PYK 2020-10-21: In my recent edit to Playing Recursion V2 >> demo examples for one liner programs I removed the copyright notice. The entire content of this wiki is intended to be in the public domain, and thus copyright notices on individual pages are unneeded and could cause confusion. See Who owns the content on this Wiki.
gold 2020-10-20. How about me just loading the pix and charts alone at the bottom of these older works by other authors? That should not spoil the looks and "optics" of the older author pages. Since my moniker is on the pix, if readers want more info, refs, and the generating code, they may contact me. I do not have an ax to grind on copyright, other than no liability to me and TCL Wiki. I have some brain fog late at night, page was overwritten somehow. I have reloaded your edit 102 from the history, with omissions per request.
gold 2021-5-8.. Removing copyright notices on <gold> authored pages as spare time allows. I do not have an ax to grind on copyright, other than no liability to me and TCL Wiki. The 2007 paper of David McFarland provided an excellent history of the quarter square multiplication algorithm in both the ancient and modern eras. The college institutes, textbooks, and computer companies in the USA that previously used the Babylonian mathematical ideas without credit may be glad to know that the Babylonian copyrights and patents expired about 4000 years ago.
from rosetta code
set seed 675248
proc rnd {} {
global seed
set s [expr {$seed * $seed}]
while {[string length $s] ne 12} {
set s [string cat 0 $s]
}
set seed [string range $s 3 8]
return $seed
}
for {set i 0} {$i < 5} {incr i} {
puts " neuwman midsquares method [rnd]"
}
neuwman midsquares method 959861 neuwman midsquares method 333139 neuwman midsquares method 981593 neuwman midsquares method 524817 neuwman midsquares method 432883
# using mathop here in spots
#legendre_prime_density function might be
proc legendre_prime_density_approx {nn} {[/ 1. [- [log $nn 1.0866 ]] ] }
# PI2(n) ~~ n/(log(n)*log(n)
# Under test, have to check syntax
# expr expression from Tcclib for legendre_tester == expr {$limit / (log($limit) - 1.08366)}
# proc legendre_tester {nn} { expr { 1./ ((log(n)*log(n) ) } }
# proc legendre_tester {limit} { }
proc legendre_tester {limit} { $limit / (log($limit) - 1.08366) * (log($limit) - 1.08366) }
puts " legendre_tester [ legendre_tester 100 ] "
# proc legendre_tester {limit} { $limit / (log($limit) - 1.08366) }
proc legendre_tester {limit } { expr {$limit / ((log($limit) - 1.08366)*(log($limit) - 1.08366))}}
puts " legendre_tester [ legendre_tester 100 ] "
puts " legendre_tester [ legendre_tester 1000 ] "
puts " legendre_tester [ legendre_tester 10000 ] "
# legendre_tester 8.063843715007492 # approximation # legendre_tester 8.063843715007492 # approximation
# legendre_tester 8.063843715007492
# legendre_tester 29.48105748747322
# legendre_tester 151.41665299041955 gold 12/22/2025. Would this be useful as a template? You can tell me different, but I most always start with working template and go coding from that template foundation.
Starting complex TCL code from scratch is not easy for me, and I daresay not easy for AI Models either. You may disagree. Using only built-in Tk icons here (no external files needed, no "image does not exist" errors).These icons (::tk::icons::error, ::tk::icons::warning, ::tk::icons::question, ::tk::icons::information) are standard in Tk 8.5+ and appear automatically when you use tk_messageBox or certain dialogs. Here is a complete, self-contained Tcl/Tk example that reliably adds buttons/icons to the top right of a window. Working code used TCL Active State on Windows 11.
gold 12/14/2025. Testing, encountered initial difficulty in saving work? Long code blocks with or unmatched wiki markup can sometimes confuse the Tcl Wiki formatting engine, especially if fences are not balanced or a line begins with markup it treats specially.
Please place any comments here with your wiki MONIKER and date, Thanks.gold12Dec2025
Note. Testing computer methods and computer program, maybe wrong numbers.
| Category Numerical Analysis | Category Toys | Category Calculator | Category Mathematics | Category Example | Toys and Games | Category Games | Category Application | Category GUI |
| Category Numerical Analysis | Category Toys | Category Calculator | Category Mathematics | Category Example | Toys and Games | Category Games | Category Application | Category GUI |