Snippets Concepts Stochastic Ito Engine

Index for Snippets Concepts Stochastic Ito Engine



Preface


gold 5/23/2026. These are snippets for Stochastic Ito Engine for Browian motion estimates. The model is intended as an exploratory framework for TCL coding. Adding references to Dr. Chiara Marletto's counterfactual framework from the book "The Science of Can and Can't" along with other perspectives. We are using modular snippets inside modular structured programs.


gold 5/23/2026. Upon review of draft page, ...


I do not have all the answers. The Ideas Seemed to work, but maybe drawbacks? When measured by the Tcl timing statements, completion times and solutions of parameters will differ on different computer set-ups. Assume a future maintainer, either AI Model or human programmer, would have to maintain code with info content and explanatory variable name in program, ref "Snippets Concepts Effects". The Nassi Shneiderman Diagrams NSD or psuedocode Flowcharts pertain to the Tool Command Language TCL computer language as well as other computer languages like Python 3, pseudocode, word logic problems, and technical reports.


For each logic condition selecting a path or calculation task, we might have one, two, or multiple deterministic branches. Attempting to adapt format to multiple probabilistic branches used in Artificial Intelligence AI Models. Then we may use the >>> lottery algorithm <<< to select the winning pathways or tickets.


The existing program has some dummy subroutines. A full construction seems too complex here. I have limited space on the wiki page, and the fill‑in for the dummy routines has to be pretty brief. In engineering terms, I’m aiming for a “90% solution”, meaning about 90% right and 10% off. Like the simple college formula for a pendulum that is not the exact time series. Call it “fake it ’til you make it” as a college try, but for Quantum Many Worlds. Who is to say? Perhaps you know, TcL specializes in GUI solutions. Maybe try and adapt some starter TcL code for a "quantum worlds slide rule ". Hopefully compatible with the hard-wired classical theory.


Limitations on Tool and Disclaimer


The TCL Snippets illustrate ideal mathematical behavior only and do not perform full simulation, actual measurements, or state vector evolution. The tool only visualizes ideal math structure, whereas no state vector simulation, probabilities, or actual measurement outcomes are derived. This tool for visualization does not simulate actual measurement outcomes or state vector evolution during operations. These are idealized protocols for tutorial purposes. Primarily, TCL /TK uses its strong points here for book keeping and displays. The example tool is not a full emulator. Meaning, limited scope for tutorial purposes.


Disclaimer. None of the computer programs, numerical experiments, power-law fits, or physical analogies described here give a strict, formal proof of the Conjectures, either individually or in combination. The tools and analogies are heuristic models and visualization tools that follow engineering “rules of thumb.” Whereas, pure mathematics has its own shop rules for what counts as a rigorous proof. Any opinions on the difficulty or plausibility reflect current understanding here and programming of the Conjectures as a very hard open problem, not a completed exact math proof, and are offered with full respect for the standards of professional mathematicians.


Extra Significant Figures, If Any in Debugging


In debugging the calculations, some of the printout values reflect roughly 17-digit precision output from a typical double-precision computation. It's not "true exact" beyond 5 significant figures. Extra significant figures are used to check the calculations from other computer set-ups, not necessarily to infer accuracy of data measurements here. Typically, the slight differences in decimal places on far right of decimal point are normal floating-point behavior in Tcl's expr.


Introduction


Tcl simulator for Brownian motion paths, Ito stochastic integrals, and simple stochastic investment strategies.


Brownian Motion


Back in 1827, a Scottish botanist named Robert Brown noticed something odd—pollen grains floating in water didn’t just drift or sink; they darted around in unpredictable, jittery patterns. Brown didn’t know why, but he was fascinated. It wasn’t until decades later that Einstein stepped in and explained the mystery: those pollen grains were constantly getting hit from all sides by water molecules bumping into them. Each collision nudged the grain just a little, and when you add up thousands of these random nudges, you get a path that never repeats or settles down.


At its core, Brownian motion has three key features. First, it starts at zero. You always know where you begin. Second, it’s memoryless. Wherever that grain is right now, the next thing it does doesn’t care about where it’s been before. Third, the result always follows a bell curve, and the spread gets wider, growing with the square root of the elapsed time.


Box-Muller Transform


The program relies on an algorithm called the Box-Muller transform. George Box and Mervin Muller came up with this method back in 1958. Here’s how it works. The algorithm grabs two random numbers that follow a uniform distribution. The standard kind and turns them into two numbers that fit a normal distribution. The algorithm does this using logarithms and trigonometric functions. The process isn’t just a rough guess. The algorithm is mathematically precise. That’s why it’s a solid choice for scientific simulations.


Kiyosi Ito Integral for Random Processes


Back in the 1940s, Kiyosi Ito, a Japanese mathematician, tackled this tricky problem by creating a whole new kind of integral for random processes. The Ito integral isn’t your typical integral. The integral function is built as a limit of sums and doesn’t rely on standard derivatives. Here’s the twist. When you calculate each tiny piece, you have to use the value of the function at the start of the interval, but not anywhere else. That’s the non-anticipating condition. Basically, the function isn’t allowed to “see into the future”. The function can only use information up to the present moment.


Application In Financial Markets


For example, in financial markets a trader cannot know or predict tomorrow's price. The non-anticipating condition isn’t just some abstract math rule. It actually matters in the real world. So, any trading strategy that makes sense has to follow this rule. That’s where the Ito integral comes in. It’s built to model the ups and downs you get when you trade this way.


Summary


This Stochastic Ito Engine brings stochastic calculus concepts to life using pure Tcl. Program nails the essentials: accurate Brownian motion, proper left-endpoint Ito integration, and hands-on simulations of stochastic strategies. The code helps you learn. Whether you’re running experiments or building something new. Descriptive names, readable output, and tables that work right out of the box make it a solid pick for teaching or studying on your own.


Wiki Table: Tcl Procedures and Concept Reference


Index Procedure Name Purpose Key Concept Quibble-Notes
1 randnormal Generates normally distributed random numbers using the Box-Muller transform Normal distribution sampling Avoid seeding with a fixed value in production; use a time-based or system-entropy seed for unique runs
2 GenerateBrownianPath Builds a discrete Brownian motion path step by step Brownian motion, square-root scaling Path log grows with step count; for large step counts consider writing to file rather than accumulating in memory
3 ComputeItoIntegralApprox Approximates an Ito integral using left-endpoint Riemann sums Ito integral, non-anticipating condition The {} expansion operator is essential when calling a stored lambda; omitting {} produces the "invalid command name" error shown in the screenshot
4 SimulateConstantIntegrand Tests integration with a constant function Constant integrand; expected result is mean-zero The expected value of the result is 0 regardless of the constant; variance equals constant-squared times the time horizon
5 ApplyVariableDeterministic Tests integration with a time-growing exponential function Deterministic time-dependent integrand The exponential growth of the integrand increases variance in the later steps; more steps are needed for stable results at longer horizons
6 RunStochasticStrategyTest Simulates three betting strategies over a sequence of random increments Martingale, proportional, and constant-bet strategies The Martingale strategy produces exponentially growing stake requirements. Need additional data clamps. Use with caution even in simulation to avoid numerical overflow at high step counts
7 runSingleItoAutotest Runs one complete test scenario and reports elapsed time Test harness, wall-clock timing Wall-clock time includes operating-system scheduling noise; for benchmarking, average over many runs
8 runAllItoAutotests Orchestrates all five test scenarios in sequence Automated testing, parameter variation Extending to ten or twenty parameter combinations would improve coverage of edge cases such as very large step counts or very long horizons
AUDIT WINDOW Program validated May 2026 All five autotests expected to pass after fix

Note. This Stochastic Ito Engine is intended for educational and math simulation purposes only. The Martingale strategy included in the code is shown purely for illustrative and theoretical math comparison for various programs. In practice, the Martingale system leads to almost certain ruin over the long run due to finite capital, capitol limits, and the possibility of long losing streaks.


References


  • Snippets Concepts Stochastic Ito Engine
  • Snippets Concepts DFT on Inference Vectors
  • Snippets Concepts Triangular Propagation
  • Snippets Concepts Inference Engine
  • Snippets Concepts Diósi Penrose Model
  • Snippets Concepts Quantum Fourier Transform
  • Snippets Concepts Lottery Pruning
  • Snippets Concepts Qubits Model
  • Snippets Concepts Collatz Plotter
  • Snippets Concepts Geometric Tunneling
  • Snippets Concepts Collatz T-Stop
  • Snippets Concepts Random Cubics
  • Snippets Concepts McCarthy 91_Function
  • Snippets Concepts Predator Prey
  • Snippets Concepts Thomas Solver
  • Snippets Concepts Grover Simulation
  • Snippets Concepts Radioactive Decay
  • Snippets Concepts Hypersphere Simulation
  • Snippets Concepts Nassi Shneiderman Flowcharts
  • Snippets Concepts SlideRule to Quantum
  • Snippets Physics Concepts Qubits
  • Snippets Physics Concepts Feynman
  • Snippets Physics Concepts Quantum
  • Snippets Physics Concepts Toy
  • Snippets Physics Concepts Minimalism
  • Zero Handling Workarounds

Note. These Snippets on Theoretical Physics are a set, not stand alones. Recommend read all of the set.


  • A little slide-rule on TCL Wiki, ( much credit for the algorithms in the sliderule. )
  • Richard Suchenwirth 2003-08-31
  • Smoothing and differentiation of data by simplified least squares procedures
  • Savitzky, A. ; Golay, M. J. E. Two examples are presented as subroutines in the FORTRAN language.
  • Savitzky Golay Filtering, Python
  • Savitzky Golay Filtering — SciPy Cookbook documentation
  • Smoothing Example with Savitzky-Golay Filter in Python
  • Introduction to the Savitzky-Golay Filter: A Comprehensive Guide (Using Python), Thomas Konstantinovsky
  • Konstantinovsky has good explanation. Note detailed. WhittakerSmoother in Python
  • The Perfect Way to Smooth Your Noisy Data, Whittaker-Eilers smoother, Andrew Bowell
  • Feb 28, 2024

  • A Basis for a Mathematical Theory of Computation,Author(s)
  • McCarthy, John
  • John McCarthy: A basis for a mathematical theory of computation, in:
  • Computer Programming and Formal Systems.
  • P.Braffort, D.Hirschberg (ed.), Amsterdam:North Holland 1963,
  • several versions, archived pdf
  • McCarthy’s LISP and Basis for Theory of Computation, archived pdf
  • en.wikipedia.org search on <John McCarthy computer>
  • John McCarthy at Stanford web site, archived
  • Towards a Mathematical Science of Computation, J. McCarthy,
  • Computer Science Department, Stanford University, archived pdf
  • Elephant 2000: A Programming Language Based on Speech Acts
  • John McCarthy, Stanford University, archived
  • Elephant input and output statements are characterized
  • as speech acts and programs, which
  • can refer directly to the past.
  • Elephant proposal contains summary
  • on McCarthy mathematical theory of computation
  • Mysteries and other Matters, development of Lisp , archived
  • Note. A lot of early papers and notes from John McCarthy and Knuth are difficult to assess web links or archived.

  • Machine Learning Approaches to the Collatz Conjecture:
  • A Comprehensive Framework for Pattern Recognition
  • and Automated Conjecture Generation. IJIRT, Vol. 12 Issue 7
  • Transformers Know More Than They Can Tell:
  • Learning the Collatz Sequence , arXiv:2511.10811
  • The Collatz conjecture, Littlewood-Offord theory, and powers of 2 and 3,
  • Aug 2011, Terence Tao,
  • mentions Gambler's Ruin on this 2011 post, but better search on his website for updates.

  • Efficient Computation of Collatz Sequence
  • Stopping Times: A Novel Algorithmic Approach ( credit for the new algorithm. )
  • EYOB SOLOMON GETACHEW, BEAKAL GIZACHEW ASSEFA
  • The Collatz Conjecture over the Gaussian Integers, Alejandra Alvarado

  • An example of the difference between quantum and classical random walks
  • Andrew M. Childs, Edward Farhi, Sam Gutmann ( much credit for the new algorithm. )

  • Simple Program Design, Lesley Anne Robertson, 2004
  • Lecture in Spanish, diagrama de nassi schneiderman o rectángular
  • website for estudia con nancho, 2023
  • Lecture, Communicating Complex Logic with Ease
  • with Nassi-Shneiderman Diagrams, Atanas Marchev,
  • Jetbrains MPS community, 2023
  • Java library for working with Nassi-Shneiderman diagrams
  • (structograms) from Atanas Marchev, Github website
  • Flowchart techniques for structured programming
  • Authors: I. Nassi, B. Shneiderman, circa 1973
  • KernelF- an Embeddable and
  • Extensible Functional Language, Markus Voelter
  • voelter = acm, ~~ 2023
  • Algorithmic Accountability: Designing for Safety , Ben Shneiderman,
  • Radcliffe Institute, 2018

  • the lottery ticket hypothesis:
  • finding sparse, trainable neural networks, jonathan frankle, mit
  • 4 mar 2019, michael carbin

  • Maria Violaris, arXiv preprint titled "Quantum observers can communicate across multiverse branches." Jan 2026
  • Vafa, Cumrun (September 2006). "Baby universes and string theory". International Journal of Modern Physics D. 15 (10): 1581–1586.
  • Lecture from Sean Carroll: The many worlds of quantum mechanics
  • Lecture from Sean Carroll: Quantum Mechanics and the Many-Worlds Interpretation
  • Lecture on many worlds theory, Does Quantum Mechanics Reveal the Secrets of Parallel Universes?
  • Emergence of Classicality in Wigner’s Friend Scenarios, Tom Rivlin, Jul 2025
  • Quantum Superpositions of Conscious States in a Minimal Integrated Information Model, Kelvin J. McQueen, April 2026
  • Wigner's friend scenarios: on what to condition and how to verify the predictions
  • Flavio Del Santo, Jul 2024
  • A review and analysis of six extended Wigner's friend arguments
  • David Schmid, Yìlè Yīng, Matthew Leifer, Aug 2023
  • The Many Worlds of Hugh Everett III : Multiple Universes,
  • Mutual Assured Destruction, and the Meltdown of a Nuclear Family
  • Peter Byrne, 2010
  • The Many-Worlds Interpretation of Quantum Mechanics (level 3 multiverse), dissertation,
  • Everett, Hugh

  • An Undergraduate Course in Quantum Computing, Peter Young, Apr 2026
  • # Based on ref. An Undergraduate Course in Quantum Computing, Peter Young, Apr 2026
  • # Much credit for the quantum circuit diagrams, Matches textbook Fig 16.4 etc
  • # University of California Santa Cruz, CA, arXiv:2604.10396
  • Does gravity follow the rules of quantum mechanics? Press Release, Prof. Kazuhiro Yamamoto
  • Momentum squeezed state realized via optimal filtering in optomechanics:
  • Implications for gravity-induced entanglement”, Ryotaro Fukuzumi, Published 13 April,2026.
  • Bose-Marletto-Vedral experiment without observable spacetime superpositions
  • Nicetu Tibau Vidal,Chiara Marletto
  • The Science of Can and Can't : A Physicist's Journey Through the Land of Counterfactuals
  • by Chiara Marletto, 2021.
  • Quantum Coins and Counterfactuals, in Consistent Quantum Theory, Robert B. Griffiths, 2002,
  • from CMU Quantum Theory Group
  • How to Rewrite the Laws of Physics in the Language of Impossibility,
  • Amanda Gefter, Contributing Writer, April 29, 2021
  • Fundamental properties of beam-splitters in classical and quantum optics: arxiv /abs/2303.13705
  • Masud Mansuripur, Ewan M. Wright, 2023
  • Constructor theory, Wikipedia, date 4/27/2026

  • Constructor theory of probability, 2016,
  • Chiara Marletto
  • Bernstein, G. A. (2026c). Reality is mathematical structure.
  • Bernstein, G. A. (2026e). Why these simple laws?
  • Deriving physics from mathematical necessity.
  • Bernstein, G. A. (2026h). The arrow of time is irreversible computation.
  • Deutsch, D. (2013). Constructor theory. Synthese, 190(18), 4331-4359.
  • Deutsch, D., & Marletto, C. (2015). Constructor theory of information. Proceedings of the Royal
  • Society A, 471(2174), 20140540.
  • Deutsch, D. (1997). The Fabric of Reality. Penguin.
  • Deutsch, D. (2011). The Beginning of Infinity. Penguin.
  • Marletto, C. (2021). The Science of Can and Can't. Penguin.
  • Popper, K. (1972). Objective Knowledge. Oxford University Press.

  • Computation: finite and infinite machines, by Minsky, Marvin Lee, Publication date 1967
  • Recursive Unsolvability of Post's Problem of "Tag" and other Topics in Theory of
  • Turing Machines, Marvin L. Minsky, 1961, pp. 437-455.
  • Computational Techniques and Computational Aids in Ancient
  • Mesopotamia, Jens Høyrup, 2018, Roskilde University, Roskilde, Denmark.
  • Lecture, Mod-01 Lec-39 Counter machines and their equivalence to basic TM model.
  • fm Theory of Computation by Prof. Somenath Biswas, Computer Science and Engineering, IIT Kanpur.
  • Turing Machine Alternative (Counter Machines) - Computerphile
  • Lecture, Computing with counters. How "counter machines" are as powerful as turing machines,
  • albeit more convoluted! Dr Christopher Hampson, Senior Lecturer in Computer Science Education, at KCL
  • Lecture, EXTRA BITS - More on Counter Machines - Computerphile
  • Algebra in Cuneiform, Introduction to an Old Babylonian Geometrical Technique
  • Jens Høyrup, 2017
  • Computational Techniques and Computational Aids in Ancient Mesopotamia
  • Jens Høyrup, 2018
  • A Note on Old Babylonian Computational Techniques
  • May 2002, Jens Egede Høyrup, Roskilde University
  • Website for Jens Egede Høyrup, Roskilde University
  • Research gate has an outstanding bibliography on
  • Jens Egede Høyrup, OB. Computation
  • Ancient Babylonian Number System Had No Zero, By Evelyn Lamb, 2014

  • Hawking’s 1975 Classic Paper, "Particle Creation by Black Holes"
  • the main Hawking radiation paper.
  • Penrose Process, Energy Extraction from Rotating Black Holes:
  • Foundational 1971 paper with R. M. Floyd:
  • Extraction of Rotational Energy from a Black Hole
  • Penrose’s 1965 Singularity Theorem
  • Gravitational Collapse and Space-Time Singularities,
  • Physical Review Letters Paper.
  • Blandford–Znajek Mechanism ,electromagnetic energy extraction
  • closely related to Penrose process :
  • 1977 Original Paper in Monthly Notices of the Royal Astronomical Society
  • Kerr Metric in 1963 Original Paper:
  • Gravitational Field of a Spinning Mass, Physical Review Letters.

Note. The ink is hardly dry on some of these papers. Don't know what gems are hidden, if I dig deeper.


Screenshots




figure. BROWNIAN MOTION PATH SIMULATION


+----------------------------------------------------------------------------------+
| 1) BROWNIAN MOTION PATH (BuildBrownPath)                                         |
|    Wiener Process W(t) - Discrete approximation                                  |
|                                                                                  |
|    Time 0.0 : Position 0.0                                                       |
|         |                                                                        |
|         v   + dW1 (random)                                                       |
|    Time dt  : Position X1                                                        |
|         |                                                                        |
|         v   + dW2                                                                |
|    Time 2dt : Position X2                                                        |
|         |          ...                                                           |
|         v                                                                        |
|    Time T   : Position XN  (random walk with sqrt(dt) scaling)                   |
|                                                                                  |
|    Each increment:   dW = sqrt(dt) * N(0,1)                                     |
|    Property: E[W(t)] = 0    Var[W(t)] = t                                        |
+----------------------------------------------------------------------------------+

figure. ITO INTEGRAL APPROXIMATION


+----------------------------------------------------------------------------------+
| 2) ITO STOCHASTIC INTEGRAL (ItoIntegApprox)                                      |
|    Left-endpoint non-anticipating sum                                            |
|                                                                                  |
|    t=0     t=dt    t=2dt   ...   t=T                                            |
|     |-------|-------|----------|                                                 |
|     v       v       v          v                                                 |
|    f(t0)   f(t1)   f(t2)  ...  f(tN-1)                                          |
|     *dW0   *dW1    *dW2   ...  *dWN                                              |
|                                                                                  |
|    Integral ≈ Σ f(t_i) * ΔW_i     (ΔW_i evaluated AFTER f(t_i))                 |
|                                                                                  |
|    Key: Integrand cannot "see" future Brownian increment                        |
+----------------------------------------------------------------------------------+

figure. CONSTANT vs EXPONENTIAL INTEGRAND


+----------------------------------------------------------------------------------+
| 3) TEST INTEGRANDS                                                               |
|                                                                                  |
|    Constant Integrand f(t) = C                                                   |
|    → Expected integral = 0                                                       |
|    → Variance = C² × T                                                           |
|                                                                                  |
|    Exponential Integrand f(t) = exp(0.5 × t)                                    |
|    → Growing function → later steps contribute more variance                     |
|                                                                                  |
|    Both approximated via ItoIntegApprox left Riemann sum                         |
+----------------------------------------------------------------------------------+

figure. STRATEGY SIMULATION ENGINE


+----------------------------------------------------------------------------------+
| 4) STOCHASTIC INVESTMENT STRATEGIES (RunStratSimTest)                           |
|                                                                                  |
|    Wealth(t+1) = Wealth(t) + Stake × ΔW                                         |
|                                                                                  |
|    [Martingale]                                                                  |
|      Stake = 2^(step-1)   (doubles after each round)                             |
|      → High risk of ruin / overflow                                              |
|                                                                                  |
|    [Proportional]                                                                |
|      Stake = 0.2 × |Wealth|   (fractional Kelly-like)                            |
|      → Wealth stays positive longer                                              |
|                                                                                  |
|    [Flatbet]                                                                     |
|      Stake = 1.0 fixed                                                           |
|                                                                                  |
|    ΔW drawn from N(0,1) each step                                                |
+----------------------------------------------------------------------------------+

figure. BOX-MULLER NORMAL GENERATOR


+----------------------------------------------------------------------------------+
| 5) DRAW NORMAL RANDOM (DrawNormalRand)                                           |
|    Box-Muller Transform                                                          |
|                                                                                  |
|    U1, U2 ~ Uniform(0,1)                                                         |
|         |                                                                        |
|         v                                                                        |
|    Z = sqrt(-2 ln U1) * cos(2π U2)                                               |
|         |                                                                        |
|         v                                                                        |
|    Normal = μ + σ × Z                                                            |
|                                                                                  |
|    Used for every Brownian increment and strategy shock                          |
+----------------------------------------------------------------------------------+

figure. OVERALL PROGRAM FLOW

+----------------------------------------------------------------------------------+
| 6) PROGRAM ORGANIZATION (RunAllItoTests)                                         |
|                                                                                  |
|    SetRandomSeed                                                                 |
|         |                                                                        |
|         v                                                                        |
|    ┌─────────────────────────────────────┐                                       |
|    │ 5 Scenarios (different steps & T)   │                                       |
|    └──────────────────┬──────────────────┘                                       |
|                       |                                                          |
|          ┌────────────┼────────────┐                                             |
|          |            |            |                                             |
|          v            v            v                                             |
|    Brownian     Ito Integrals   Strategy Sims                                    |
|      Path      (Const + Exp)    (Proportional)                                   |
|          |            |            |                                             |
|          └────────────┼────────────┘                                             |
|                       v                                                          |
|                PrintSummStats (Min/Max/Mean)                                     |
|                       |                                                          |
|                       v                                                          |
|                   Edge Case Tests                                                |
|                (T=0, steps=1, steps=1000)                                        |
+----------------------------------------------------------------------------------+

figure. EDGE CASE BEHAVIOUR


+----------------------------------------------------------------------------------+
| 7) EDGE CASE BATTERY                                                             |
|                                                                                  |
|    Edge A: T = 0.0          → All increments = 0.0 (exact zero integral)         |
|                                                                                  |
|    Edge B: 1000 steps       → Fine grid, mean → 0, variance → theoretical value  |
|                                                                                  |
|    Tests robustness of ItoIntegApprox and random number handling                 |
+----------------------------------------------------------------------------------+

Appendix Code


Appendix TCL Programs and Scripts


1. Expanded Toy for Demo



Experimenting Draft


This is a draft.



Trial Test Program




Testing Extended deck


Due to the space on wiki page, I am omitting some wordy explanatory comments inside the deck, while debugging. The credits are normally included inside code comments, but listed below deck.


# Stochastic Ito Engine for Brownian Motion  V4
# Tcl 8.6 or greater required
# Naming convention: all proc and variable names are 12-15
# characters, descriptive, and domain-neutral so the engine
# can serve any subject area without modification.
# Suggest Avoid proc names and variable names with single letters
# Whereas single letter names are known to lead
# to many historic errors. 
# 
# ----
# Compatible with Tcl/Tk (Tool Command Language / Toolkit) 8.6+
# Written for Windows 11 on ActiveState Tcl.
# Use Pure 7-bit ASCII code, no Unicode characters used anywhere.
# ----
# Program deck may contain multiple estimation procs.
# Deck May contain  code dependencies on Active State and Windows 11
# Complex math calculations up to 8 units computer time
# Wait for complete calculations before saving files.
# Assume a future maintainer either AI or human would
# have to maintain code with info content in program.
#
# This is a hacker's patch, not rigorously derived.
# appears correct solutions for autotests.
# TCL Club 5/25/2026 
# =============================================================================
# PURPOSE: Simulate Brownian motion paths, Ito integral approximations,
#          and stochastic investment strategies.
# NAMING CONVENTION: All proc and variable names are 12-15 characters,
#   descriptive, and domain-neutral. Single-letter names are prohibited.
# =============================================================================
console show

# -----------------------------------------------------------------------------
# New: File Logging Setup
# -----------------------------------------------------------------------------
set log_filename "ito_simulation_[clock format [clock seconds] -format %Y%m%d_%H%M%S].log"
set log_file [open $log_filename w]
puts "Console output being logged to: $log_filename"

proc LogToFile {text} {
    global log_file
    puts $log_file $text
    puts $text
}

# -----------------------------------------------------------------------------
# SetRandomSeed
# -----------------------------------------------------------------------------
proc SetRandomSeed {seed_int_val} {
    if {$seed_int_val < 0} {
        expr {srand([clock microseconds])}
        LogToFile "Seed source   : system clock (non-reproducible run)"
    } else {
        expr {srand($seed_int_val)}
        LogToFile "Seed value    : $seed_int_val (fully reproducible run)"
    }
}

# -----------------------------------------------------------------------------
# DrawNormalRand
# -----------------------------------------------------------------------------
proc DrawNormalRand {mean_location spread_factor} {
    set first_uniform  [expr {rand()}]
    set second_uniform [expr {rand()}]

    set epsilon_floor  1.0e-15
    if {$first_uniform < $epsilon_floor} {
        set first_uniform $epsilon_floor
    }

    set math_pi_value  3.14159265358979
    set normal_sample  [expr {
        sqrt(-2.0 * log($first_uniform)) *
        cos(2.0 * $math_pi_value * $second_uniform)
    }]
    return [expr {$mean_location + $spread_factor * $normal_sample}]
}

# -----------------------------------------------------------------------------
# BuildBrownPath
# -----------------------------------------------------------------------------
proc BuildBrownPath {total_step_cnt time_horizon} {
    set step_duration  [expr {double($time_horizon) / $total_step_cnt}]
    set running_postn  0.0
    set path_log_list  {}
    lappend path_log_list "Time 0.0 : Position 0.0"

    for {set step_counter 1} {$step_counter <= $total_step_cnt} {incr step_counter} {
        set path_increment [expr {sqrt($step_duration) * [DrawNormalRand 0.0 1.0]}]
        set running_postn  [expr {$running_postn + $path_increment}]
        set elapsed_time   [expr {$step_counter * $step_duration}]
        lappend path_log_list "Time $elapsed_time : Position $running_postn"
    }
    return $path_log_list
}

# -----------------------------------------------------------------------------
# PrintBrownianWikiTable -  Robust Version
# -----------------------------------------------------------------------------
proc PrintBrownianWikiTable {brownian_path total_step_cnt time_horizon scenario_num} {
    LogToFile "\n%| Index | Time (s)   | Position       | Quibble-Notes          |%"

    set sample_points 11
    set max_idx [expr {[llength $brownian_path] - 1}]
    
    for {set i 0} {$i < $sample_points} {incr i} {
        # Better sampling - works well even with 1 step
        set idx [expr {int($i * $max_idx / double($sample_points - 1))}]
        if {$idx > $max_idx} { set idx $max_idx }
        
        set entry [lindex $brownian_path $idx]
        regexp {Time ([\d\.]+) : Position ([\d\.\-]+)} $entry -> t pos
        
        # Clean formatting
        set time_clean [format "%.4f" $t]
        set pos_clean  [format "%.6f" $pos]
        
        set note [expr {$i == 0 ? "Start" : 
                       ($i == $sample_points-1 ? "End" : "Intermediate")}]
        
        LogToFile "&| $i | $time_clean | $pos_clean | $note |&"
    }
    
    LogToFile "&| AUDIT Window | | | Brownian motion sample - Scenario $scenario_num |&"
    LogToFile ""
}
# -----------------------------------------------------------------------------
# ItoIntegApprox
# -----------------------------------------------------------------------------
proc ItoIntegApprox {total_step_cnt time_horizon integrand_func} {
    set step_duration  [expr {double($time_horizon) / $total_step_cnt}]
    set integral_value 0.0
    set elapsed_time   0.0

    for {set step_counter 1} {$step_counter <= $total_step_cnt} {incr step_counter} {
        set integrand_val  [{*}$integrand_func $elapsed_time]
        set brownian_incr  [expr {sqrt($step_duration) * [DrawNormalRand 0.0 1.0]}]
        set integral_value [expr {$integral_value + $integrand_val * $brownian_incr}]
        set elapsed_time   [expr {$elapsed_time + $step_duration}]
    }
    return $integral_value
}

# -----------------------------------------------------------------------------
# RunConstIntgnd
# -----------------------------------------------------------------------------
proc RunConstIntgnd {const_val_inp total_step_cnt time_horizon} {
    set const_intg_lam [list apply \
        {{const_level_in time_input_val} {expr {$const_level_in}}} \
        $const_val_inp]
    set const_intg_val [ItoIntegApprox $total_step_cnt $time_horizon $const_intg_lam]
    LogToFile "  Const integrand=$const_val_inp  T=$time_horizon  result=$const_intg_val"
    return $const_intg_val
}

# -----------------------------------------------------------------------------
# RunExpIntegral
# -----------------------------------------------------------------------------
proc RunExpIntegral {total_step_cnt time_horizon} {
    set exp_intg_lambda {apply {{time_input_val} {expr {exp(0.5 * $time_input_val)}}}}
    set exp_intg_value  [ItoIntegApprox $total_step_cnt $time_horizon $exp_intg_lambda]
    LogToFile "  Exp  integrand  T=$time_horizon  result=$exp_intg_value"
    return $exp_intg_value
}

# -----------------------------------------------------------------------------
# RunStratSimTest
# -----------------------------------------------------------------------------
proc RunStratSimTest {strategy_type total_step_cnt} {
    set wealth_amount  1.0
    for {set step_idx_num 1} {$step_idx_num <= $total_step_cnt} {incr step_idx_num} {
        set wiener_incrmnt [DrawNormalRand 0.0 1.0]

        if {$strategy_type eq "martingale"} {
            set stake_amount   [expr {pow(2.0, $step_idx_num - 1)}]
            if {$stake_amount > 1.0e12} { set stake_amount 1.0e12 }
        } elseif {$strategy_type eq "proportional"} {
            set stake_amount   [expr {0.2 * abs($wealth_amount)}]
        } else {
            set stake_amount   1.0
        }
        set wealth_amount  [expr {$wealth_amount + $stake_amount * $wiener_incrmnt}]
    }
    LogToFile "  Strategy=$strategy_type  steps=$total_step_cnt  final_wealth=$wealth_amount"
    return $wealth_amount
}

# -----------------------------------------------------------------------------
# PrintSummStats
# -----------------------------------------------------------------------------
proc PrintSummStats {result_num_lst label_text_str} {
    set list_item_cnt  [llength $result_num_lst]
    if {$list_item_cnt == 0} {
        LogToFile "  PrintSummStats: empty list passed for '$label_text_str'"
        return
    }
    set running_total  0.0
    set minimum_value  [lindex $result_num_lst 0]
    set maximum_value  [lindex $result_num_lst 0]
    foreach each_rslt_val $result_num_lst {
        set running_total [expr {$running_total + $each_rslt_val}]
        if {$each_rslt_val < $minimum_value} { set minimum_value $each_rslt_val }
        if {$each_rslt_val > $maximum_value} { set maximum_value $each_rslt_val }
    }
    set mean_average   [expr {$running_total / $list_item_cnt}]
    LogToFile ""
    LogToFile "  --- $label_text_str ---"
    LogToFile "  N=$list_item_cnt  Min=$minimum_value  Max=$maximum_value  Mean=$mean_average"
}

# -----------------------------------------------------------------------------
# RunSingleItoScn
# -----------------------------------------------------------------------------
proc RunSingleItoScn {test_idx_num total_step_cnt time_horizon test_label_str} {
    LogToFile "--------------------------------------------------------------"
    LogToFile "  Scenario $test_idx_num : $test_label_str"
    LogToFile "  Steps = $total_step_cnt    Horizon = $time_horizon"
    LogToFile "--------------------------------------------------------------"

    set start_time_ms  [clock milliseconds]
    set brownian_path  [BuildBrownPath $total_step_cnt $time_horizon]
    # replace line here LogToFile "  Path endpoint  : [lindex $brownian_path end]"
    # Clean endpoint display
    set endpoint [lindex $brownian_path end]
    regexp {Time ([\d\.]+) : Position ([\d\.\-]+)} $endpoint -> et ep
    LogToFile "  Path endpoint  : Time [format %.4f $et] : Position [format %.6f $ep]"
    set const_intg_val [RunConstIntgnd  2.5 $total_step_cnt $time_horizon]
    set exp_intg_value [RunExpIntegral      $total_step_cnt $time_horizon]
    set strat_sim_val  [RunStratSimTest "proportional" $total_step_cnt]

    PrintBrownianWikiTable $brownian_path $total_step_cnt $time_horizon $test_idx_num

    set finish_time_ms [clock milliseconds]
    set elapsed_ms_val [expr {$finish_time_ms - $start_time_ms}]
    LogToFile "  Duration       : ${elapsed_ms_val} ms"
    LogToFile ""
    return [list $const_intg_val $exp_intg_value $strat_sim_val]
}

# -----------------------------------------------------------------------------
# RunEdgeCaseSet
# -----------------------------------------------------------------------------
proc RunEdgeCaseSet_tester {} {
    LogToFile "\n=============================="
    LogToFile "  EDGE CASE TESTS"
    LogToFile "=============================="

    RunSingleItoScn "E1"  1   1.0  "Single-step minimum"
    RunSingleItoScn "E2" 10   0.001 "Tiny time horizon"
    RunSingleItoScn "E3" 500  5.0  "Large step count, long horizon"
}
# -----------------------------------------------------------------------------
# RunEdgeCaseSet
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# RunEdgeCaseSet Notes
# Purpose  : Test program behaviour under extreme conditions to verify
#            numerical stability and correctness of Brownian motion & Ito
#            integral approximations.
#   Edge 1 : Very small time horizon (T=0.001)   → Tests near-zero behaviour
#   Edge 2 : Large number of steps (500 steps, T=5.0) → Tests fine resolution
#            and long-run statistics
#   Edge ? : Single-step minimum case omitted here, but available internal
# -----------------------------------------------------------------------------
proc RunEdgeCaseSet {} {
    LogToFile "\n=============================="
    LogToFile "  EDGE CASE TESTS"
    LogToFile "=============================="

    # Removed E1 (Single-step) - low educational value and ugly table
    RunSingleItoScn "E1" 10    0.001  "Tiny time horizon"
    RunSingleItoScn "E2" 500   5.0    "Large step count, long horizon"
}
# -----------------------------------------------------------------------------
# RunAllItoTests
# -----------------------------------------------------------------------------
proc RunAllItoTests {} {
    LogToFile "============================================================"
    LogToFile "  ITO STOCHASTIC ENGINE - FULL TEST SUITE"
    LogToFile "============================================================"

    SetRandomSeed 42

    set all_const_vals {}
    set all_exp_vals   {}
    set all_strat_vals {}

    set scenarios {
        {1   50  1.0  "Base case, fine steps"}
        {2  100  2.0  "Medium horizon"}
        {3  200  0.5  "High resolution, short time"}
        {4   80  1.5  "Variable deterministic focus"}
        {5  150  1.0  "Strategy comparison focus"}
    }

    foreach scn $scenarios {
        lassign $scn idx steps horizon label
        set results [RunSingleItoScn $idx $steps $horizon $label]
        lappend all_const_vals [lindex $results 0]
        lappend all_exp_vals   [lindex $results 1]
        lappend all_strat_vals [lindex $results 2]
    }

    PrintSummStats $all_const_vals "Constant Integrand Results"
    PrintSummStats $all_exp_vals   "Exponential Integrand Results"
    PrintSummStats $all_strat_vals "Proportional Strategy Results"

    RunEdgeCaseSet

    LogToFile "\n============================================================"
    LogToFile "  ALL TESTS COMPLETE"
    LogToFile "============================================================"
}

# -----------------------------------------------------------------------------
# MAIN ENTRY POINT
# -----------------------------------------------------------------------------
RunAllItoTests

close $log_file
puts "\nSimulation completed. Log saved as: $log_filename"

# =============================================================================
# SUGGESTED 5 AUTOTESTS FOR WIKI / CLASSROOM USE
# =============================================================================
# Test 1  : 50 steps,  T=1.0   → Base case, fine steps
# Test 2  : 100 steps, T=2.0   → Medium horizon
# Test 3  : 200 steps, T=0.5   → High resolution, short time
# Test 4  : 80 steps,  T=1.5   → Variable deterministic focus
# Test 5  : 150 steps, T=1.0   → Strategy comparison focus
#
# These five tests give excellent educational coverage:
# from gentle introduction → stress testing resolution → strategy behavior.
# The wiki tables provide clear visual snapshots of Brownian motion.
# ============================================== 
# End of file


# References.
# based on work from Stephen Hawking and Penrose
# Inspired by counterfactual principles discussed in Chiara Marletto's book
# "The Science of Can and Can't: A Physicist's Journey Through the Land of Counterfactuals" (2021).
# No text, quotes, or direct examples from the book are used in this code.
# The dummy subroutine implements a generic axiom for educational purposes only.
puts "=============================================================="
puts "Credits"
puts "Reference: Maria Violaris, arXiv:2601.08102v1, January 2026"
puts "Reference: https://wiki.tcl-lang.org/page/Snippets+Quantum+Many+Worlds"
puts "Based on ref. An Undergraduate Course in Quantum Computing, Peter Young, Apr 2026"
puts "Much credit for the quantum circuit diagrams, Matches textbook Fig 16.4 etc"
puts "University of California Santa Cruz, CA, arXiv:2604.10396"

Result in Wiki Tables from Active State


============================================================

  ITO STOCHASTIC ENGINE - FULL TEST SUITE

============================================================


Seed value : 42 (fully reproducible run)


  Scenario 1 : Base case, fine steps
  Steps = 50    Horizon = 1.0

  Path endpoint  : Time 1.0000 : Position 0.137473
  Const integrand=2.5  T=1.0  result=-3.8993006618072314
  Exp  integrand  T=1.0  result=-0.3773911585234545
  Strategy=proportional  steps=50  final_wealth=0.301327031985692

Index Time (s) Position Quibble-Notes
0 0.0000 0.000000 Start
1 0.1000 0.094675 Intermediate
2 0.2000 0.341301 Intermediate
3 0.3000 0.056301 Intermediate
4 0.4000 0.176868 Intermediate
5 0.5000 -0.571398 Intermediate
6 0.6000 0.077276 Intermediate
7 0.7000 0.174794 Intermediate
8 0.8000 0.151044 Intermediate
9 0.9000 0.367908 Intermediate
10 1.0000 0.137473 End
AUDIT Window Brownian motion sample - Scenario 1

  Duration       : 296 ms

  Scenario 2 : Medium horizon
  Steps = 100    Horizon = 2.0

  Path endpoint  : Time 2.0000 : Position -1.098753
  Const integrand=2.5  T=2.0  result=-1.093054927988484
  Exp  integrand  T=2.0  result=-1.1910916273294758
  Strategy=proportional  steps=100  final_wealth=0.020034050250369882

Index Time (s) Position Quibble-Notes
0 0.0000 0.000000 Start
1 0.2000 -0.040440 Intermediate
2 0.4000 0.678202 Intermediate
3 0.6000 0.846261 Intermediate
4 0.8000 0.849279 Intermediate
5 1.0000 1.237930 Intermediate
6 1.2000 0.866937 Intermediate
7 1.4000 0.270319 Intermediate
8 1.6000 -0.345756 Intermediate
9 1.8000 -0.537896 Intermediate
10 2.0000 -1.098753 End
AUDIT Window Brownian motion sample - Scenario 2

  Duration       : 243 ms

  Scenario 3 : High resolution, short time
  Steps = 200    Horizon = 0.5

  Path endpoint  : Time 0.5000 : Position 0.603830
  Const integrand=2.5  T=0.5  result=2.2966880225786284
  Exp  integrand  T=0.5  result=0.18280105228230348
  Strategy=proportional  steps=200  final_wealth=0.004367616525721856

Index Time (s) Position Quibble-Notes
0 0.0000 0.000000 Start
1 0.0500 -0.055086 Intermediate
2 0.1000 0.054191 Intermediate
3 0.1500 0.169364 Intermediate
4 0.2000 0.310783 Intermediate
5 0.2500 0.489530 Intermediate
6 0.3000 0.313061 Intermediate
7 0.3500 0.466650 Intermediate
8 0.4000 0.810778 Intermediate
9 0.4500 0.991978 Intermediate
10 0.5000 0.603830 End
AUDIT Window Brownian motion sample - Scenario 3

  Duration       : 239 ms

  Scenario 4 : Variable deterministic focus
  Steps = 80    Horizon = 1.5

  Path endpoint  : Time 1.5000 : Position 0.209704
  Const integrand=2.5  T=1.5  result=-4.562094350347374
  Exp  integrand  T=1.5  result=-2.982315572659521
  Strategy=proportional  steps=80  final_wealth=0.031117153479102173

Index Time (s) Position Quibble-Notes
0 0.0000 0.000000 Start
1 0.1500 0.601290 Intermediate
2 0.3000 0.424792 Intermediate
3 0.4500 0.805142 Intermediate
4 0.6000 0.613182 Intermediate
5 0.7500 0.788414 Intermediate
6 0.9000 1.195619 Intermediate
7 1.0500 1.130284 Intermediate
8 1.2000 1.106828 Intermediate
9 1.3500 0.569491 Intermediate
10 1.5000 0.209704 End
AUDIT Window Brownian motion sample - Scenario 4

  Duration       : 237 ms

  Scenario 5 : Strategy comparison focus
  Steps = 150    Horizon = 1.0

  Path endpoint  : Time 1.0000 : Position -0.216889
  Const integrand=2.5  T=1.0  result=-1.2752588078366989
  Exp  integrand  T=1.0  result=0.2754887182631123
  Strategy=proportional  steps=150  final_wealth=0.17237605692949065

Index Time (s) Position Quibble-Notes
0 0.0000 0.000000 Start
1 0.1000 0.448650 Intermediate
2 0.2000 0.448050 Intermediate
3 0.3000 0.755862 Intermediate
4 0.4000 0.492186 Intermediate
5 0.5000 0.265195 Intermediate
6 0.6000 0.213441 Intermediate
7 0.7000 0.140948 Intermediate
8 0.8000 0.140851 Intermediate
9 0.9000 0.208964 Intermediate
10 1.0000 -0.216889 End
AUDIT Window Brownian motion sample - Scenario 5

  Duration       : 241 ms


  --- Constant Integrand Results ---
  N=5  Min=-4.562094350347374  Max=2.2966880225786284  Mean=-1.706604145080232

  --- Exponential Integrand Results ---
  N=5  Min=-2.982315572659521  Max=0.2754887182631123  Mean=-0.8185017175934071

  --- Proportional Strategy Results ---
  N=5  Min=0.004367616525721856  Max=0.301327031985692  Mean=0.1058443818340753

==============================

  EDGE CASE TESTS

==============================


  Scenario E1 : Tiny time horizon
  Steps = 10    Horizon = 0.001

  Path endpoint  : Time 0.0010 : Position -0.009956
  Const integrand=2.5  T=0.001  result=0.03167693450350207
  Exp  integrand  T=0.001  result=0.02899640052438681
  Strategy=proportional  steps=10  final_wealth=1.2102344662791649

Index Time (s) Position Quibble-Notes
0 0.0000 0.000000 Start
1 0.0001 -0.016113 Intermediate
2 0.0002 -0.025189 Intermediate
3 0.0003 -0.028588 Intermediate
4 0.0004 -0.010639 Intermediate
5 0.0005 -0.035719 Intermediate
6 0.0006 -0.043663 Intermediate
7 0.0007 -0.024999 Intermediate
8 0.0008 -0.008405 Intermediate
9 0.0009 -0.007941 Intermediate
10 0.0010 -0.009956 End
AUDIT Window Brownian motion sample - Scenario E1

  Duration       : 234 ms

  Scenario E2 : Large step count, long horizon
  Steps = 500    Horizon = 5.0

  Path endpoint  : Time 5.0000 : Position -0.827591
  Const integrand=2.5  T=5.0  result=6.072901891117041
  Exp  integrand  T=5.0  result=3.073597698188631
  Strategy=proportional  steps=500  final_wealth=1.2975130435852348e-6

Index Time (s) Position Quibble-Notes
0 0.0000 0.000000 Start
1 0.5000 -0.740367 Intermediate
2 1.0000 -1.970376 Intermediate
3 1.5000 -1.809493 Intermediate
4 2.0000 -2.794824 Intermediate
5 2.5000 -2.680734 Intermediate
6 3.0000 -1.331820 Intermediate
7 3.5000 -0.449395 Intermediate
8 4.0000 -0.688809 Intermediate
9 4.5000 -0.555828 Intermediate
10 5.0000 -0.827591 End
AUDIT Window Brownian motion sample - Scenario E2

  Duration       : 248 ms


============================================================
  ALL TESTS COMPLETE
============================================================

Note. Duration is how long it took for that specific scenario to run (in milliseconds). Duration = Computation / Execution Time


gold 2/9/2026. Added categories, so can find message in Wiki.



Hidden Comments Section


Program Change Log

gold 2/3/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.


gold 2/14/2026. Added Automatic Dump of Examples, Using ActiveState.


gold 2/14/2026. convert to strict 7-bit ASCII for Playground V9. reporting error at bottom. program should run to completion with automatic test suite.


gold 2/14/2026.



gold 3/7/2026. convert to strict 7-bit ASCII for Playground V9. variables need to be human readable and very explanatory. avoid variables with single letter names. Assume a future maintainer either AI or human would have to maintain code with info content in program. the program is working the numbers correctly . so minimal changes.


gold 5/23/2026. Forwarding Python version to other venue. The TCL version is posted here.


Matrix of Collatz solutions look like two swarms of bees rather a single linear solution or even look like multiple fuzzy levels of solution ranges, eg. non-linear solutions, observable in various pngs. You can tell me different. Based on long experience of fitting equations in engineering, possibly the probabilistic reasoning or pattern matching on quantum solutions plural is more adaptable.


gold 4/24/2026. Difficult for me to evaluate the Quantum math theories. The Python versions are posted in other venues. The TCL version is posted on wiki.


However, I suppose that the simulation model using TcL could check the Yada-Yada theory for consistencies with other vouched quantum rules. However, code seems interesting from a hack programming viewpoint. 





Please place any comments here with your wiki MONIKER and date, Thanks.gold 5/10/2026



Note. Testing computer methods and computer programs, maybe wrong numbers.