Snippets Concepts Qubits Model


Index for Snippets Concepts Qubits Model


Preface

gold 2/9/2026. Here are some simple snippets for numerical methods. The goal is to use Tcl's minimalism as a learning tool. Snippets are short procs that let one play with one core concept at a time. All snippets are Playground V9 safe. One approach to the subject of theoretical physics is to consider these Tcl snippets as Toys. Some snippets here are listed as Toys. These Tcl procs are tiny entry points into physics. On the Wiki Playground V9, Change numbers, add loops, or combine them to explore. Tcl's expr and list/dict make it easy to "feel" the "heavy" ideas without heavy machinery.


Limitations on Tool


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.



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


The page presents Tcl code snippets. These educational examples aim to make coding accessible through minimalist programming on the Tcl Playground V9 platform. The following analysis examines how the code implements principles, evaluates the floating-point precision observed in outputs, and suggests improvements for clarity and educational value.


Body



Key Steps


Draft on Protocol


gold This is a draft. 2/11/2026


Quantum Teleportation Modeled As a sheet of Paper


{ User } Advisor requests similar to previous snippets, but on topic of Qubit Model solution. The advisor stated that a possible model of quantum teleportation is a sheet of paper folded in half to create two lips with the symbols +_+ on both lips. Fold the paper so that the lips touch. The main loop of the paper is the distance of space-time between the qubits. Imagine a cross section of the paper sheet as a "V" or "Vee" shape. This is a model of quantum teleportation. I do not have all the answers. The Ideas Seemed to work, but maybe drawbacks?


PRACTICAL VISUALIZATION AND TIPS


Building the paper model requires only basic materials: a sheet of paper, a pen or marker, and optionally some tape. Starting with a standard letter-sized sheet, fold the paper exactly in half lengthwise. Press the fold firmly to create a sharp crease representing strong entanglement. Draw symbols on the edges near each end of the fold to create the "lips" showing quantum states. These symbols might include plus signs, minus signs, or arrows pointing up or down to represent qubit states.


Demonstrating quantum measurement with the model involves marking one lip and observing the corresponding change at the other lip. When a measurement collapses the quantum state of one qubit, mark this on one lip with a specific symbol. The entanglement means the other qubit's state also becomes determined, so mark the corresponding symbol on the other lip immediately. This represents the instantaneous correlation between entangled particles. However, to complete teleportation, trace the path around the loop with a finger or pen, showing that classical information must travel this longer distance.


Comparing different quantum states becomes possible by creating multiple paper models. A model with very close lips (small loop) represents qubits separated by a short distance, where classical communication takes little time. A model with lips far apart (large loop) represents qubits separated by large distances, where classical communication becomes the limiting factor. Creating models with different fold qualities demonstrates how entanglement strength affects teleportation success. A sharp fold represents high-quality entanglement, while a loose or multiple fold represents degraded entanglement.


EXTENSIONS AND ADVANCED CONCEPTS


The basic paper model extends to represent more complex quantum phenomena. Three or more entangled qubits could use paper folded into a fan shape, where multiple folds represent multiple entanglement connections. Quantum error correction might be modeled using multiple sheets of paper stacked together, where redundancy in the sheets represents redundancy in quantum codes. These extensions help students and researchers visualize increasingly sophisticated quantum protocols.


Connecting the paper model to mathematical descriptions strengthens understanding. The quantum state of a qubit exists as a superposition, written mathematically as α|0⟩ + β|1⟩, where α and β represent complex probability amplitudes. The symbols on the paper lips represent these states, while the fold represents the entangled state |φ⁺⟩ = (|00⟩ + |11⟩)/√2 or similar Bell states. Manipulating the paper demonstrates unitary operations on qubits, and measuring collapses the superposition to a definite state shown by the final symbols.


CONCLUSION AND ACTIONABLE STEPS


The paper folding model provides an accessible entry point for understanding quantum teleportation's essential features: entanglement creates a connection (the fold), quantum states transfer through this connection (symbols appearing on both lips), and classical communication remains necessary (the path around the loop). Building physical models helps students and researchers develop intuition about abstract quantum phenomena. Experimenting with different paper sizes, fold configurations, and symbol systems allows exploration of how distance, entanglement quality, and quantum states affect teleportation protocols.


Rationale of Paper-Folding Model and Set of Directions


A simple paper-folding model that demonstrates quantum teleportation for beginners tutorial. The model uses everyday paper to show how quantum information moves from one place to another without traveling through normal space. Readers will find printed ASCII directions, a wiki-format table that summarizes the steps, and added notes that clarify qubit symbols and quantum reasoning.


The paper model starts with a single sheet of paper folded in half. This fold creates two lips that represent two qubits. The left lip stands for the qubit that holds the state to teleport, sender. The right lip stands for the qubit that receives the state, receiver. Symbols written on the lips show quantum states or equivalent quantum bits such as zero or one.


Quantum teleportation requires three main resources. First, entanglement links the two qubits so their states stay connected even when far apart. Second, a measurement on the sender side collapses the quantum state into classical bits. Third, classical communication sends those bits to the receiver side. The receiver uses the bits to adjust its qubit and recover the original state. The fold at the bottom of the paper represents the entangled pair, often called an Einstein-Podolsky-Rosen pair or EPR pair. The long loop around the outside of the paper represents the distance in normal space-time.


The key teaching point is that the quantum state does not jump instantly across the loop. The state only appears correctly on the receiving side after the classical bits complete their journey around the loop. This shows that quantum teleportation respects the speed-of-light limit for information transfer.


Actionable Steps Summary


Maintain single-purpose TCL procedures under 30 lines each. Test TCL invariants after every transformation. Use descriptive names embedding physics meaning in the TCL code. Convert tabs to spaces uniformly. Print variable states at computation boundaries. These steps transform debugging into verification process reliably. Tool Control Language thrives under disciplined practices in scientific work.



Proposed Tweaks to Paper Model



gold 2/21/2026. Advisor requests similar to previous snippets, but on topic of .... That visual model of folding paper to represent spacetime connection for teleportation is quite evocative as it reminds me of ... Paper Model also captures the non-local entanglement aspect well. What about trying to translate that concept into some TCL snippets illustrating the geometry or state evolution. If it can be clarified what the '+_+' symbols represent precisely. A 2d surface is mapped to a 4D hypersphere.


gold 2/21/2026. Those '+_+' symbols for the Paper Model represent one or other of the 4 states of Bell Pairs. Clear that deeper explanation and more intuitive symbols than "+-+" for the 4 Bell quantum pairs are needed for the paper model. However, its easier to program the 'mental gymnastics and meaningful pseudocode', if the cards for Wild-Card and Jokers??? are presented up front on the table. I do not have all the answers. The Ideas seemed to work, but maybe drawbacks?


Seeks refinements to symbolic placeholders ("+_+" ) in a paper model of quantum teleportation. Proposed symbols would represent the four Bell states of entangled qubits. Entangled qubits are crucial for transmitting quantum information without physical particle transfer. Bell pairs consist of four orthogonal states:

# Tcl
set bell_pair_lister {
    "Φ+ = (|00⟩ + |11⟩)/√2"
    "Φ- = (|00⟩ - |11⟩)/√2"
    "Ψ+ = (|01⟩ + |10⟩)/√2"
    "Ψ- = (|01⟩ - |10⟩)/√2"
}
# possibly pull context from list assignment
set phi_plus   [lindex $bell_pair_lister 0]
set phi_minus  [lindex $bell_pair_lister 1]
set psi_plus   [lindex $bell_pair_lister 2]
set psi_minus  [lindex $bell_pair_lister 3]
# lindex returns the element at the given zero‑based index.
# or else, Using lassign (multiple assignment)
# tcl
lassign $bell_pair_lister phi_plus phi_minus psi_plus psi_minus

Concepts were formalized in the 1993 Bennett et al. paper, enabling secure key distribution and computation. Intuitive alternatives to "+_+" include matrix visualizations, or else, icons like interlocking rings for entanglement. Better symbols would enhance accessibility in educational models per studies on quantum visualization in Physical Review A (2018).


Educational Applications


The program demonstrates math patterns.


The strict ASCII constraint ensures compatibility with collegiate IT lab environments where students may work across diverse platforms and text editors. The implementation deliberately omits boundary closure bars during active development to simplify debugging, with plans to add them once testing completes.



Table 1 : Features on Quantum Teleportation Fidelity Simulator, Tcl Program,



Index Aspect Value / Observation Notes
1 Script version feature Fidelity normalization added After adding noise, Bob's state vector is re-normalized (norm = 1.0). This ensures fidelity is always ≤ 1.0000 — physically correct and eliminates artifact values > 1.0 from earlier versions.
2 Fidelity mathematical bound Always 0.0 ≤ fidelity ≤ 1.0000 Guaranteed by Cauchy-Schwarz inequality once states are unit vectors. Previous non-normalized runs sometimes showed small excesses (e.g. 1.02–1.05) due to norm > 1 after noise. Fixed here.
3 Randomness in simulation Results vary on every run due to Tcl's rand() Noise strength and (in autotest) state phase angles use random numbers. Re-running gives different fidelity values each time. For reproducible results, one could replace rand() with fixed seeds or constant values.
4 Noise model characteristics Additive Gaussian-like noise on real parts only Very simple educational model (noise ~ uniform-max/2, +max/2). Real decoherence is more complex (amplitude damping, phase damping, depolarizing channels), but this suffices to demonstrate fidelity drops.
5 Typical fidelity range (20 trials) Usually 0.94–0.999+ Depends on drawn noise level (0.01–0.15 range). Higher noise → larger drop. Average often ~0.97–0.99 in normalized version.
6 Example fidelity interpretation > 0.99 = near-perfect teleportation 0.98–0.99 = excellent (typical good lab results)<br>0.95–0.98 = moderate noise impact<br>< 0.95 = higher noise case (intended to show failure modes)
7 Purpose of autotest loop Monte-Carlo style demonstration of variability Runs 20 trials with different Bloch-sphere states + random noise levels → shows statistical spread. Useful for teaching how fidelity behaves under imperfect conditions.
8 Input state parametrization angleTheta = trial × π / 11 Spreads states roughly across the Bloch sphere equator (imaginary part varies via phase). Not full sphere coverage, but sufficient for demo. Alpha real = cos(θ/2), Beta complex = sin(θ/2) × e^(iφ).
9 Recommended future improvements Add full Bloch-sphere sampling, Pauli noise model, stats Could include min/max/stddev of fidelities, histogram output, fixed seed via srand, CSV export, or comparison to theoretical fidelity bounds.
10 Compatibility Pure Tcl 8.5+ (no packages required) Uses only built-ins: expr, rand, format, puts, for, set, list, lindex, sqrt, cos, sin. Runs on Tcl Playground, ActiveState, tclsh, etc.

Note. Cutoff date for table is 2/12/2026 with limited trial runs. "We" expect to learn more in proofing runs.


Table : Tcl Quality Guidelines


Priority What good Tcl code usually has What to avoid Physics Relevance Notes
1 Extremely clear names x, tmp, data, temp1 Momentum p → fourMomentum, z → celestialZ, ε → variationParameter Clarity > brevity; physicists already spend cognitive load on concepts — don’t add more on variable names
2 Functions < 20–30 lines 200-line monsters One function ≈ one conceptual step (e.g. boost, projection, soft insertion) Short procs mirror short proof steps — easier to verify correctness
3 One level of abstraction per function Mix business + low-level details Separate kinematics (4-vectors) from holographic map (z,\bar z) Prevents mixing bulk physics with boundary CFT logic — aids conceptual separation
4 Consistent naming convention camelCase + snake_case mix Use snake_case for Tcl procs/vars (four_momentum, soft_factor) Consistency reduces mental overhead when reading derivations or code
5 Meaningful distinction between similar concepts user, usr, userData, theUser Avoid p, pp, p_mu, pprime — prefer incoming_momentum, outgoing_momentum In physics, small notation differences can hide big conceptual errors
6 Comments only when WHY is not obvious Explaining WHAT good names already say Comment the physical motivation (“# soft pole regulated for numerics”) Most physicists read code like proofs — let names carry the story; comment intent
7 Domain language over technical language processEntities → approveCustomerOrders celestial_projection instead of map_to_sphere_coordinates Use the language of celestial amplitudes, soft theorems, BMS group — makes code feel like theory


Table. Use Extremely Descriptive, Honest Names (The #1 Rule)


Index number on draft is arbitrary.



# Bad / Cryptic Good / Self-explaining Why better?
1 x, tmp, data, i, res userAgeInYears, temporaryPassword, allProducts Immediately tells purpose
2 calc, process, doStuff calculateTotalPriceWithTax, sendWelcomeEmail Reveals what and why
3 getUser findUserByEmail / getCurrentlyLoggedInUser Different behaviors → different names
4 flag, status isAccountActive, hasPaymentFailed, orderShipped Boolean names should answer questions with yes/no
5 n, len, cnt numberOfActiveUsers, totalItemsInCart Avoid abbreviations unless universal (i→index ok)

Note. Avoid one letter shortcuts on variable names.



CVS Version of Table


Index number on draft is arbitrary.


"#","Bad / Cryptic","Good / Self-explaining","Why better?"
"1","x, tmp, data, i, res","userAgeInYears, temporaryPassword, allProducts","Immediately tells purpose"
"2","calc, process, doStuff","calculateTotalPriceWithTax, sendWelcomeEmail","Reveals what and why"
"3","getUser","findUserByEmail / getCurrentlyLoggedInUser","Different behaviors → different names"
"4","flag, status","isAccountActive, hasPaymentFailed, orderShipped","Boolean names should answer questions with yes/no"
"5","n, len, cnt","numberOfActiveUsers, totalItemsInCart","Avoid abbreviations unless universal (i→index ok)"


Table. Naming Variables, Code Quality Guidelines


Priority What good code usually has What to avoid
1 Extremely clear names x, tmp, data, temp1
2 Functions < 20–30 lines 200-line monsters
3 One level of abstraction per function Mix business + low-level details
4 Consistent naming convention camelCase + snake_case mix
5 Meaningful distinction between similar concepts user, usr, userData, theUser
6 Comments only when WHY is not obvious Explaining WHAT good names already say
7 Domain language over technical language processEntities → approveCustomerOrders

Note. Avoid one letter shortcuts on variable names.


CVS Version of Table


"Priority","What good code usually has","What to avoid"
"1","Extremely clear names","x, tmp, data, temp1"
"2","Functions < 20–30 lines","200-line monsters"
"3","One level of abstraction per function","Mix business + low-level details"
"4","Consistent naming convention","camelCase + snake_case mix"
"5","Meaningful distinction between similar concepts","user, usr, userData, theUser"
"6","Comments only when WHY is not obvious","Explaining WHAT good names already say"
"7","Domain language over technical language","processEntities → approveCustomerOrders" 

Directions for Paper Model of Quantum Teleportation


1. Take one sheet of plain paper.
2. Fold the paper in half from bottom to top so the two top edges (lips) meet.
3. The fold at the bottom now represents the EPR pair (entanglement link).
4. The main loop of paper around the outside represents space-time distance.
5. On the left lip, write the symbol |ψ⟩ to show the state to teleport.
6. On the right lip, write |0⟩ to show the starting state of the receiver qubit.
7. To simulate measurement: touch the left lip and erase |ψ⟩.
8. Write a classical result on the left lip (example: |0⟩ or |1⟩).
9. Trace a finger along the outside loop from left to right to show classical bits traveling.
10. When the finger reaches the right lip, erase |0⟩.
11. Write |ψ⟩ on the right lip.
12. Explain: the state |ψ⟩ now appears on the right only after classical info arrives.

Table. Directions for Paper Model of Quantum Teleportation


Index Step or Concept Description Notes
1 Prepare the paper Fold sheet in half to create two lips and a bottom fold The fold represents entanglement; lips represent qubits; loop represents space-time distance. No instant jump occurs.
2 Write initial states Left lip: (ψ⟩ (state to send); Right lip: (0⟩ (receiver starts empty) {ψ⟩ means "any quantum state" (example: 0.8(0⟩ + 0.6{1⟩); (0⟩ means ground state. Symbols are labels, not magic.
3 Entanglement link Point to the bottom fold as EPR pair EPR pair = two qubits sharing special correlation; changes to one affect the other instantly, but usable info still needs classical channel.
4 Perform measurement on sender Touch left lip, erase {ψ⟩, write classical result (0 or 1) Measurement collapses superposition to one outcome; this is random but correlated due to entanglement.
5 Send classical bits Trace finger along outside loop from left to right This path is slow (light speed limit); shows why teleportation is not faster-than-light communication.
6 Reconstruct state at receiver When finger reaches right lip, erase {0⟩ and write {ψ⟩ Receiver uses classical bits to apply correction gates (X or Z); final state matches original.
7 Key teaching point State appears on right only AFTER classical info arrives Prevents violation of relativity; entanglement provides correlation, classical channel provides usable information.
8 Why symbols matter {ψ⟩ and {0⟩ are just labels for quantum states Treat symbols as shorthand for probability amplitudes; no mystical power — they follow math rules like vectors.
9 Common confusion "Does the state jump instantly?" No — the correlation is instant, but extracting and using the teleported state requires the slow classical step.
10 For future models Use model to train intuition on no-signaling theorem Practice explaining why entanglement enables teleportation without sending faster-than-light signals; builds correct reasoning.



Note. Cutoff date for table is 2/12/2026 with limited trial runs. "We" expect to learn more in proofing runs. Unfortunately, some of the quantum math symbols like "pipe | " and "ampersand &" conflict with the table format for the Wiki. Try as best. Esp. use the CVS Version of Table if conflicted.



CVS Version of Table



"Index","Step or Concept","Description","Notes" 1,"Prepare the paper","Fold sheet in half to create two lips and a bottom fold","The fold represents entanglement; lips represent qubits; loop represents space-time distance. No instant jump occurs." 2,"Write initial states","Left lip: |ψ⟩ (state to send); Right lip: |0⟩ (receiver starts empty)","|ψ⟩ means ""any quantum state"" (example: 0.8|0⟩ + 0.6|1⟩); |0⟩ means ground state. Symbols are labels, not magic." 3,"Entanglement link","Point to the bottom fold as EPR pair","EPR pair = two qubits sharing special correlation; changes to one affect the other instantly, but usable info still needs classical channel." 4,"Perform measurement on sender","Touch left lip, erase |ψ⟩, write classical result (0 or 1)","Measurement collapses superposition to one outcome; this is random but correlated due to entanglement." 5,"Send classical bits","Trace finger along outside loop from left to right","This path is slow (light speed limit); shows why teleportation is not faster-than-light communication." 6,"Reconstruct state at receiver","When finger reaches right lip, erase |0⟩ and write |ψ⟩","Receiver uses classical bits to apply correction gates (X or Z); final state matches original." 7,"Key teaching point","State appears on right only AFTER classical info arrives","Prevents violation of relativity; entanglement provides correlation, classical channel provides usable information." 8,"Why symbols matter","|ψ⟩ and |0⟩ are just labels for quantum states","Treat symbols as shorthand for probability amplitudes; no mystical power — they follow math rules like vectors." 9,"Common confusion","""Does the state jump instantly?""","No — the correlation is instant, but extracting and using the teleported state requires the slow classical step." 10,"For future models","Use model to train intuition on no-signaling theorem","Practice explaining why entanglement enables teleportation without sending faster-than-light signals; builds correct reasoning."


Table. Comparing number of lines and comments in TCL 8.6 & Python 3.14+ Versions, Reorg' Code


# 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 splits doc across docstrings instead
3 Docstring delimiter lines (""") n/a 28 Python only; one open + one close per function; no TCL equivalent
4 Blank / whitespace lines 38 86 Python style guide (PEP 8) requires two blank lines between top-level defs
5 Executable code lines (derived) 262 417 Total minus hash-comments minus docstring delimiters minus blanks
6 Comment-to-total ratio 47.5 pct 28.0 pct TCL front-loads the entire tutorial in one comment block at the top
7 Code-to-total ratio 45.9 pct 59.7 pct Python carries more executable lines; type hints add one line per argument
8 Python code overhead vs TCL -- +155 lines +59.2 pct more executable lines; match statement and type annotations are verbose

Note. If you counted docstring body lines as documentation, Python's true code count would fall closer to 300, making the two languages more comparable.


Note. Python spreads the same information across per-function docstrings, which is why its hash count is lower but its blank-line count is higher.


Note. This table is not intended as an installment of TCL versus Python wars, etc. Trying a full-up of NASA/JPL rules and human understandable code as understood here. It has occurred to me that the NASA/JPL rules might be putting a straight jacket on both languages. There is a faint memory of byte code optimizing, which was not considered here. The NASA/JPL rules were written for spacecraft where a human inspector must read and sign each procedure in isolation. An estimated 1.84x runtime penalty for NASA/JPL rules against a 10-microsecond TCL baseline is irrelevant on a Mars rover. However, in a possible college IT lab simulation running millions of trials, it adds up to a genuine overhead cost worth noting in the wiki.


CVS Version of Table


Index,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 splits doc across docstrings instead
3,Docstring delimiter lines ("""),n/a,28,Python only; one open + one close per function; no TCL equivalent
4,Blank / whitespace lines,38,86,Python style guide (PEP 8) requires two blank lines between top-level defs
5,Executable code lines (derived),262,417,Total minus hash-comments minus docstring delimiters minus blanks
6,Comment-to-total ratio,47.5 pct,28.0 pct,TCL front-loads the entire tutorial in one comment block at the top
7,Code-to-total ratio,45.9 pct,59.7 pct,Python carries more executable lines; type hints add one line per argument
8,Python code overhead vs TCL,--,+155 lines,+59.2 pct more executable lines; match statement and type annotations are verbose

Screenshots Section



figure 1.


figure. Snippets Physics Concepts Qubits screenshot Fidelity, from Playground V9


testing plot concept here, no frills


Snippets Physics Concepts Qubits screenshot Fidelity



figure 2.



figure. Snippets Concepts Radioactive Decay Playground Plot


Note. Exponential Deay curve is concept used in many of my models.


Snippets Concepts Radioactive Decay Playground Plot


figure. Snippets Concepts Qubits Model sheet2


Snippets Concepts Qubits Model sheet2


figure. Snippets Concepts Qubits Model paper


Snippets Concepts Qubits Model paper


figure. Snippets Concepts Qubits Model use


Snippets Concepts Qubits Model use2




figure. Snippets Concepts Qubits Model extensions


Snippets Concepts Qubits Model extensions


Snippets Concepts Qubits Model Grid Model


References


  • 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.


Appendix Code


Appendix TCL Programs and Scripts


1. Expanded Toy for Demo


This is a draft, still debugging on Playground V9. convert to strict 7-bit ASCII for Playground V9.



# Quantum Teleportation Fidelity Simulator with Noise V4
# toy on wiki page 
# ================================================================
# Quantum Teleportation Fidelity Simulator with Simple Noise Model
# Educational / demonstration script - strict 7-bit ASCII only
# Intended for Tcl Playground or minimal Tcl interpreters
# 2025-2026 version - heavily commented for future maintainers
# ================================================================
# may have to check strict ASCII for Playground V9
# Compatible with Tcl/Tk 8.6+
# TCL source code follows
# Written for Windows 11 on ActiveState Tcl
# Working on TCL Playground V9, strict ASCII only
# Optimized for collegiate IT lab environments
# Working under TCL version 8.6
# Complex math calculations up to 3 units computer time
# Wait for complete calculations before saving files.
# TCL club, 02/12/2026
# This is a hacker's patch, not rigorously derived.
# appears correct autotest
# pure ASCII code - no Unicode characters used anywhere
puts "Quantum Teleportation Fidelity Simulator with Noise"
puts "---------------------------------------------------"
puts "  (state normalized after noise → fidelity <= 1.0)"
puts ""

# ----------------------------------------------------------------
# Procedure: Calculate how close the teleported state is to original
#            Includes optional random noise to simulate real-world
#            imperfections (decoherence, gate errors, etc.)
#            Now normalizes Bob's state after noise so norm=1.
# ----------------------------------------------------------------
proc CalculateTeleportationFidelityWithNoise \
    {inputAlphaRealPart inputAlphaImagPart \
     inputBetaRealPart  inputBetaImagPart  \
     {maximumNoiseAmplitude 0.05}} {

    # ------------------------------------------------------------------------
    # Bob ideally receives exactly the same state Alice sent
    # We start by copying the input coefficients to Bob's reconstructed state
    # ------------------------------------------------------------------------
    set bobReconstructedAlphaReal $inputAlphaRealPart
    set bobReconstructedAlphaImag $inputAlphaImagPart
    set bobReconstructedBetaReal  $inputBetaRealPart
    set bobReconstructedBetaImag  $inputBetaImagPart

    # --------------------------------------------------------------------
    # Simulate small random errors (very simple decoherence / gate noise)
    # Noise is added only to the real parts in this toy model
    # --------------------------------------------------------------------
    set randomNoiseForAlpha [expr {$maximumNoiseAmplitude * (rand() - 0.5)}]
    set randomNoiseForBeta  [expr {$maximumNoiseAmplitude * (rand() - 0.5)}]

    set bobReconstructedAlphaReal \
        [expr {$bobReconstructedAlphaReal + $randomNoiseForAlpha}]

    set bobReconstructedBetaReal \
        [expr {$bobReconstructedBetaReal + $randomNoiseForBeta}]

    # --------------------------------------------------------------------
    # NEW: Re-normalize Bob's state vector so ||psi|| = 1
    #     This is physically required and prevents fidelity > 1.0
    # --------------------------------------------------------------------
    set currentNormSquared \
        [expr {$bobReconstructedAlphaReal**2 + \
               $bobReconstructedAlphaImag**2 + \
               $bobReconstructedBetaReal**2  + \
               $bobReconstructedBetaImag**2}]

    if {$currentNormSquared > 0.0} {
        set normalizationScaleFactor [expr {1.0 / sqrt($currentNormSquared)}]

        set bobReconstructedAlphaReal \
            [expr {$bobReconstructedAlphaReal * $normalizationScaleFactor}]

        set bobReconstructedAlphaImag \
            [expr {$bobReconstructedAlphaImag * $normalizationScaleFactor}]

        set bobReconstructedBetaReal \
            [expr {$bobReconstructedBetaReal * $normalizationScaleFactor}]

        set bobReconstructedBetaImag \
            [expr {$bobReconstructedBetaImag * $normalizationScaleFactor}]
    }
    # (if norm was exactly zero — extremely unlikely — we leave it alone)

    # --------------------------------------------------------------------
    # Compute the complex inner product <input_state | bob_state>
    # (overlap between original and received state)
    # --------------------------------------------------------------------
    set realPartOfOverlap \
        [expr {$inputAlphaRealPart * $bobReconstructedAlphaReal + \
               $inputAlphaImagPart * $bobReconstructedAlphaImag + \
               $inputBetaRealPart  * $bobReconstructedBetaReal  + \
               $inputBetaImagPart  * $bobReconstructedBetaImag}]

    set imagPartOfOverlap \
        [expr {$inputAlphaRealPart * $bobReconstructedBetaImag  - \
               $inputAlphaImagPart * $bobReconstructedBetaReal  + \
               $inputBetaRealPart  * $bobReconstructedAlphaImag  - \
               $inputBetaImagPart  * $bobReconstructedAlphaReal}]

    # --------------------------------------------------------------------
    # Fidelity = |<input|bob>|^2   (now guaranteed 0 <= fidelity <= 1)
    # --------------------------------------------------------------------
    set fidelityValue \
        [expr {$realPartOfOverlap * $realPartOfOverlap + \
               $imagPartOfOverlap  * $imagPartOfOverlap}]

    # Return list containing Bob's coefficients + final fidelity
    return [list $bobReconstructedAlphaReal \
                 $bobReconstructedAlphaImag \
                 $bobReconstructedBetaReal \
                 $bobReconstructedBetaImag \
                 $fidelityValue]
}

# --------------------------------------------------------------------
# Helper to print one result line in readable format
# --------------------------------------------------------------------
proc PrintSingleFidelityResult {description \
                                alphaReal alphaImag \
                                betaReal  betaImag  \
                                fidelity} {

    puts [format "%-26s  %8.4f + %8.4fi   %8.4f + %8.4fi   fidelity = %.4f" \
                 $description \
                 $alphaReal $alphaImag \
                 $betaReal  $betaImag \
                 $fidelity]
}

# ===============================================
#               EXAMPLE RUNS
# ===============================================

puts "Example runs:"
puts ""

# Example 1 - approximate state (not perfectly normalized input)
set resultList [CalculateTeleportationFidelityWithNoise 0.8 0.0 0.6 0.0 0.02]
PrintSingleFidelityResult "~ 0.8|0> + 0.6|1>" {*}$resultList

# Example 2 - Hadamard / plus state (|0> + |1>)/sqrt(2)
set resultList [CalculateTeleportationFidelityWithNoise 0.7071 0.0 0.7071 0.0 0.10]
PrintSingleFidelityResult "(|0> + |1>)/sqrt(2)" {*}$resultList

puts ""
puts ""

# ===============================================
#               AUTOTEST / BENCHMARK SECTION
# ===============================================

puts "AUTOTEST: 20 independent trials with varied states and noise"
puts "------------------------------------------------------------"
puts " Trial   State approx description      Noise    Fidelity  "
puts "------------------------------------------------------------"

set sumOfAllFidelities 0.0
set numberOfTrialsCompleted 0

for {set trialNumber 1} {$trialNumber <= 20} {incr trialNumber} {

    # Create test state using angle parameterization (Bloch sphere style)
    set angleTheta [expr {$trialNumber * 3.1415926535 / 11.0}]

    set inputAlphaReal [expr {cos($angleTheta / 2.0)}]
    set inputAlphaImag 0.0

    set inputBetaReal  [expr {sin($angleTheta / 2.0) * cos($trialNumber * 0.7)}]
    set inputBetaImag  [expr {sin($angleTheta / 2.0) * sin($trialNumber * 0.7)}]

    # Noise strength varies randomly between 1% and 15%
    set noiseStrengthThisTrial [expr {0.01 + 0.14 * rand()}]

    set resultList \
        [CalculateTeleportationFidelityWithNoise \
             $inputAlphaReal $inputAlphaImag \
             $inputBetaReal  $inputBetaImag  \
             $noiseStrengthThisTrial]

    set thisTrialFidelity [lindex $resultList 4]

    set shortStateDescription [format "cos(%.2f/2)|0> + ..." $angleTheta]

    puts [format "%5d   %-24s   %5.3f    %.4f" \
                 $trialNumber \
                 $shortStateDescription \
                 $noiseStrengthThisTrial \
                 $thisTrialFidelity]

    set sumOfAllFidelities [expr {$sumOfAllFidelities + $thisTrialFidelity}]
    incr numberOfTrialsCompleted
}

set averageFidelity [expr {$sumOfAllFidelities / $numberOfTrialsCompleted}]

puts "------------------------------------------------------------"
puts "Average fidelity across $numberOfTrialsCompleted trials : [format %.4f $averageFidelity]"
puts "Note: fidelity is now guaranteed <= 1.0000 due to normalization"
puts "Done."
puts ""

Expected console output


gold 2/12/2026. Actual numbers vary because of rand()) in use.


Quantum Teleportation Fidelity Simulator with Noise


Example runs:

|psi> ≈ 0.8|0> + 0.6|1>     0.8023 + 0.0000i   0.5971 + 0.0000i   fidelity = 0.9998
|+> = ( |0> + |1> )/√2     0.7104 + 0.0000i   0.6992 + 0.0000i   fidelity = 0.9872


AUTOTEST: 20 trials with different states and noise levels
----------------------------------------------------------
  Trial   State description           Noise   Fidelity
----------------------------------------------------------
   1    cos(0.29/2)|0> + ...        0.042    0.9987
   2    cos(0.57/2)|0> + ...        0.118    0.9721
   3    cos(0.86/2)|0> + ...        0.031    0.9992
...
  20    cos(5.71/2)|0> + ...        0.089    0.9845
----------------------------------------------------------
Average fidelity over 20 trials : 0.9876
Note: values < 1.0 come from added noise (decoherence/gate error model)
Done. 

Output from ActiveState



Quantum Teleportation Fidelity Simulator with Noise

Example runs:

|psi> ≈ 0.8|0> + 0.6|1>  0.7950 + 0.0000i   0.5928 + 0.0000i   fidelity = 0.9835
|+> = ( |0> + |1> )/√2  0.7127 + 0.0000i   0.6598 + 0.0000i   fidelity = 0.9418


AUTOTEST: 20 trials with different states and noise levels
----------------------------------------------------------
  Trial   State description           Noise   Fidelity
----------------------------------------------------------
   1    cos(0.29/2)|0> + ...    0.119    0.8930
   2    cos(0.57/2)|0> + ...    0.069    1.0217
   3    cos(0.86/2)|0> + ...    0.077    0.9522
   4    cos(1.14/2)|0> + ...    0.057    1.0486
   5    cos(1.43/2)|0> + ...    0.028    0.9874
   6    cos(1.71/2)|0> + ...    0.067    0.9913
   7    cos(2.00/2)|0> + ...    0.023    0.9996
   8    cos(2.28/2)|0> + ...    0.127    0.9663
   9    cos(2.57/2)|0> + ...    0.084    1.0263
  10    cos(2.86/2)|0> + ...    0.013    1.0101
  11    cos(3.14/2)|0> + ...    0.105    1.0089
  12    cos(3.43/2)|0> + ...    0.040    1.0222
  13    cos(3.71/2)|0> + ...    0.060    0.9851
  14    cos(4.00/2)|0> + ...    0.032    1.0269
  15    cos(4.28/2)|0> + ...    0.049    0.9928
  16    cos(4.57/2)|0> + ...    0.144    0.9770
  17    cos(4.86/2)|0> + ...    0.113    0.9614
  18    cos(5.14/2)|0> + ...    0.136    0.9502
  19    cos(5.43/2)|0> + ...    0.110    0.9375
  20    cos(5.71/2)|0> + ...    0.019    1.0069
----------------------------------------------------------
Average fidelity over 20 trials : 0.9883
Note: values < 1.0 come from added noise (decoherence/gate error model)
Done.

Outputs from Playground V9


>     set total_fid [expr {$total_fid + $fid}]
>     incr count
> }
   1    cos(0.29/2)|0> + ...    0.148    0.8878
   2    cos(0.57/2)|0> + ...    0.079    0.9417
   3    cos(0.86/2)|0> + ...    0.138    1.1251
   4    cos(1.14/2)|0> + ...    0.020    0.9779
   5    cos(1.43/2)|0> + ...    0.039    1.0238
   6    cos(1.71/2)|0> + ...    0.063    1.0482
   7    cos(2.00/2)|0> + ...    0.084    1.0366
   8    cos(2.28/2)|0> + ...    0.028    1.0104
   9    cos(2.57/2)|0> + ...    0.136    0.8994
  10    cos(2.86/2)|0> + ...    0.093    0.9916
  11    cos(3.14/2)|0> + ...    0.146    1.0213
  12    cos(3.43/2)|0> + ...    0.056    1.0356
  13    cos(3.71/2)|0> + ...    0.063    0.9626
  14    cos(4.00/2)|0> + ...    0.020    1.0164
  15    cos(4.28/2)|0> + ...    0.063    0.9751
  16    cos(4.57/2)|0> + ...    0.016    0.9913
  17    cos(4.86/2)|0> + ...    0.059    1.0155
  18    cos(5.14/2)|0> + ...    0.061    0.9745
  19    cos(5.43/2)|0> + ...    0.030    0.9825
  20    cos(5.71/2)|0> + ...    0.069    1.0287
(tcl) 28 % 
(tcl) 28 % set avg [expr {$total_fid / $count}]
0.9973089741691569
(tcl) 29 % puts "----------------------------------------------------------"
----------------------------------------------------------
(tcl) 30 % puts "Average fidelity over 20 trials : [format %.4f $avg]"
Average fidelity over 20 trials : 0.9973
(tcl) 31 % puts "Note: values < 1.0 come from added noise (decoherence/gate error model)"
Note: values < 1.0 come from added noise (decoherence/gate error model)
(tcl) 32 % puts "Done.\n"
Done.

Normalized Fidelity {for Bob} from Playground. See difference from Fidelity == 1.0 in right column.


]
> 
>     set sumOfAllFidelities [expr {$sumOfAllFidelities + $thisTrialFidelity}]
>     incr numberOfTrialsCompleted
> }
    1   cos(0.29/2)|0> + ...       0.132    0.9973
    2   cos(0.57/2)|0> + ...       0.033    1.0000
    3   cos(0.86/2)|0> + ...       0.043    0.9999
    4   cos(1.14/2)|0> + ...       0.146    0.9984
    5   cos(1.43/2)|0> + ...       0.148    0.9997
    6   cos(1.71/2)|0> + ...       0.084    0.9987
    7   cos(2.00/2)|0> + ...       0.061    1.0000
    8   cos(2.28/2)|0> + ...       0.068    0.9990
    9   cos(2.57/2)|0> + ...       0.015    1.0000
   10   cos(2.86/2)|0> + ...       0.099    0.9984
   11   cos(3.14/2)|0> + ...       0.110    1.0000
   12   cos(3.43/2)|0> + ...       0.038    0.9996
   13   cos(3.71/2)|0> + ...       0.105    0.9986
   14   cos(4.00/2)|0> + ...       0.086    0.9997
   15   cos(4.28/2)|0> + ...       0.114    0.9981
   16   cos(4.57/2)|0> + ...       0.038    1.0000
   17   cos(4.86/2)|0> + ...       0.119    0.9983
   18   cos(5.14/2)|0> + ...       0.119    0.9996
   19   cos(5.43/2)|0> + ...       0.066    1.0000
   20   cos(5.71/2)|0> + ...       0.104    0.9999
(tcl) 60 % 
(tcl) 60 % set averageFidelity [expr {$sumOfAllFidelities / $numberOfTrialsCompleted}]
0.9992615945463484
(tcl) 61 % 
(tcl) 61 % puts "------------------------------------------------------------"
------------------------------------------------------------
(tcl) 62 % puts "Average fidelity across $numberOfTrialsCompleted trials : [format %.4f $averageFidelity]"
Average fidelity across 20 trials : 0.9993
(tcl) 63 % puts "Note: fidelity is now guaranteed <= 1.0000 due to normalization"
Note: fidelity is now guaranteed <= 1.0000 due to normalization
(tcl) 64 % puts "Done."
Done.
(tcl) 65 % puts ""

(


Toy Solver for bell_states_reorg_v2.tcl



This is a draft, still debugging on Playground V9. convert to strict 7-bit ASCII for Playground V9.


# Run tests automatically when sourced



Output from Playground V9


# trial ouput, no frills.
(tcl) 24 % 
(tcl) 24 % # Automatically run tests when script loads
(tcl) 25 % run_autotests
Test phi+ matching bits: PASS (mismatches: 0)
Test phi- matching bits: PASS (mismatches: 0)
Test psi+ opposite bits: PASS (same-bit cases: 0)
Test psi- opposite bits: PASS (same-bit cases: 0)

Overall: ALL TESTS PASSED


Output from ActiveState


Bell States Simulator Reorg V2 - Sample Measurements

Examples for phi-plus (matching bits -- same arrow on both lips):
  Trial  1:  Alice -> 0    Bob -> 0
  Trial  2:  Alice -> 0    Bob -> 0
  Trial  3:  Alice -> 0    Bob -> 0
  Trial  4:  Alice -> 1    Bob -> 1
  Trial  5:  Alice -> 1    Bob -> 1
  Trial  6:  Alice -> 1    Bob -> 1
  Trial  7:  Alice -> 0    Bob -> 0
  Trial  8:  Alice -> 0    Bob -> 0

Examples for psi-minus (opposite bits -- arrows point opposite directions):
  Trial  1:  Alice -> 0    Bob -> 1
  Trial  2:  Alice -> 0    Bob -> 1
  Trial  3:  Alice -> 1    Bob -> 0
  Trial  4:  Alice -> 0    Bob -> 1
  Trial  5:  Alice -> 1    Bob -> 0
  Trial  6:  Alice -> 1    Bob -> 0
  Trial  7:  Alice -> 0    Bob -> 1
  Trial  8:  Alice -> 1    Bob -> 0

==============================================================
 Bell States Simulator Reorg V2 - Seven Autotests
 TCL Club 02/2026 -- Quantum Entanglement Correlation Verifier
==============================================================

Paper-fold analogy: crease = entangled link between two qubits.
phi-plus / phi-minus : both lips show same arrow  (matching bits).
psi-plus / psi-minus : lips show opposite arrows  (opposite bits).

--- Autotest 1 ---
  Input  : Bell state phi-plus  (matching-outcome state)
  Expect : Alice bit == Bob bit on every trial
  Trials : 500
  Output : PASS -- all 500 trials matched

--- Autotest 2 ---
  Input  : Bell state phi-minus  (matching-outcome state)
  Expect : Alice bit == Bob bit on every trial
  Trials : 500
  Output : PASS -- all 500 trials matched

--- Autotest 3 ---
  Input  : Bell state psi-plus  (opposite-outcome state)
  Expect : Alice bit != Bob bit on every trial
  Trials : 500
  Output : PASS -- all 500 trials were opposite

--- Autotest 4 ---
  Input  : Bell state psi-minus  (opposite-outcome state)
  Expect : Alice bit != Bob bit on every trial
  Trials : 500
  Output : PASS -- all 500 trials were opposite

--- Autotest 5 ---
  Input  : invalid Bell state name = 'phi_plus'
  Expect : assertion error raised (defensive guard fires)
  Output : PASS -- error correctly raised: ASSERTION FAILED: simulateSingleBellMeasurement: unknown Bell state 'phi_plus'

--- Autotest 6 ---
  Input  : invalid Bell state name = ''
  Expect : assertion error raised (defensive guard fires)
  Output : PASS -- error correctly raised: ASSERTION FAILED: simulateSingleBellMeasurement: unknown Bell state ''

--- Autotest 7 ---
  Input  : Bell state phi-plus  (timing measurement)
  Expect : average microseconds per call reported
  Output : 9.5716 microseconds per call (1000-iteration average)

==============================================================
 All 7 autotests completed successfully. ALL TESTS PASSED.
==============================================================

Page Is Under Development


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 5Jan2026



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/4/2026. Added Automatic Dump of Examples, Using ActiveState. Added temp double hatch border, ##.


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



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



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