Snippets Physics Concepts Qubits


Index for Snippets Physics Concepts Qubits


Preface

gold 2/3/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 theoretical 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 quantum circuit simulation, actual measurements, or state vector evolution. The quantum circuit tool only visualizes circuit 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 gate 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 quantum 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.



Advisor requests similar to previous snippets, but on topic of computing circuits ref Deutsch. I do not have all the answers. The Ideas Seemed to work, but maybe drawbacks?


Introduction


The page presents Tcl code snippets demonstrating three fundamental quantum computing concepts: superposition, entanglement, and interference. These educational examples aim to make quantum mechanics accessible through minimalist programming on the Tcl Playground V9 platform. The following analysis examines how the code implements quantum principles, evaluates the floating-point precision observed in outputs, and suggests improvements for clarity and educational value.


Body



Quantum teleportation is a beautiful protocol that transfers an unknown quantum state from one qubit (Alice's message qubit) to a distant qubit (Bob's qubit) using entanglement and classical communication . All without physically moving the particle or violating relativity.


The protocol relies on a shared Bell state as a maximally entangled EPR pair, a Bell measurement by Alice, and corrective gates by Bob based on two classical bits that Alice sends. The No-Cloning theorem prevents direct copying of quantum states. But the teleportation protocol circumvents this by "destroying" the original state during measurement and reconstructing the state remotely. This is an idealized protocol for tutorial purposes.


Key Steps


Qubit Protocol


Prepare entanglement: Alice and Bob share a Bell state. The Bell state is usually |Φ⁺⟩ = (|00⟩ + |11⟩)/√2 on Alice's qubit B and Bob's qubit C. Created by Hadamard on one qubit + CNOT.


Alice entangles message with her share: Apply CNOT (message qubit A control → B target), then Hadamard on A.


Bell measurement: Alice measures qubits A and B in computational basis. This is equivalent to Bell basis via the inverse circuit. Gets two classical bits (either 00, 01, 10, or 11).


Classical communication: Alice sends the two bits to Bob.


Bob corrects in this manner:

----
Depending on bits:
----
00: do nothing
01: apply X (bit flip)
10: apply Z (phase flip)
11: apply X then Z (or ZX)
Bob's qubit C ends up exactly in the original state of A.
----
Now, Bob's Qubit C equals the original state of  Alice's Qubit A.


The state or message is teleported perfectly, but requires classical bits and limited to light speed. This is an idealized protocol for tutorial purposes. There is no faster-than-light information transfer in this ideal case.


Gist of Tcl Snippet


Amplitude Simulation of Quantum Teleportation (n=1 qubit, 3-qubit system). This 8–10 line Tcl proc simulates amplitudes through the protocol steps for a simple input state |ψ⟩ = α|0⟩ + β|1⟩. Here α=1, β=0 for |0⟩;real α=0.707, complex β=0.707i for superposition; α=0.8, β=0.6. The proc tracks the final amplitude on Bob's qubit after correction. Code has Strict ASCII, human-readable names, autotesting with example.



Background Definitions on Quantum Gates


Quantum gates are the fundamental building blocks of quantum circuits, analogous to logic gates (AND, OR, NOT) in classical computing. But Quantum gates operate on qubits rather than bits. Also, Quantum gates exploit quantum principles like superposition, interference, and entanglement. Classical gates produce deterministic outputs. Quantum gates are reversible and represented by unitary matrices. Meaning, applying the Quantum gate and then, its inverse returns the original state, and probabilities are preserved.


Key Properties of Quantum Gates


Quantum Gates act linearly on the quantum state vector.


Single-qubit gates use 2×2 unitary matrices; two-qubit gates use 4×4 matrices, and so on (2ⁿ × 2ⁿ for n qubits).


All quantum gates are reversible. Information is never lost.


Measurement collapses the state, but gates themselves do not measure.


Background Definitions on Bell States


The Bell states are the four maximally entangled two-qubit states. Also, the Bell states are called EPR pairs after Einstein, Podolsky, and Rosen. The Bell states represent the simplest and most fundamental form of quantum entanglement. The four Bell states are:


Φ⁺⟩ = (|00⟩ + |11⟩)/√2  
Φ⁻⟩ = (|00⟩ - |11⟩)/√2  
Ψ⁺⟩ = (|01⟩ + |10⟩)/√2  
Ψ⁻⟩ = (|01⟩ - |10⟩)/√2

The most commonly created and discussed one is |Φ⁺⟩, the symmetric Bell state.


How to Create the Bell State |Φ⁺⟩


Start with two qubits, both in the ground state: |00⟩.The standard quantum circuit uses just two gates: Apply a Hadamard gate (H) to the first qubit (control qubit).


This creates superposition: |00⟩ → (|0⟩ + |1⟩)|0⟩ / √2 = (|00⟩ + |10⟩)/√2


Apply a controlled-NOT (CNOT) gate with the first qubit as control and the second qubit as target. If control is |0⟩ → target stays unchanged.


If control is |1⟩ → target flips (|0⟩ → |1⟩)


Result: (|00⟩ + |10⟩)/√2 → (|00⟩ + |11⟩)/√2 = |Φ⁺⟩


This is the canonical Bell state creation circuit:


q0 (control): |0⟩ ───H─────•───── |Φ⁺⟩ first qubit


q1 (target): |0⟩ ─────────X───── |Φ⁺⟩ second qubit


The Hadamard puts the control qubit into superposition.


The CNOT "copies" that superposition onto the target qubit in a correlated way, creating entanglement



Background on Feynman and Deutsch


Richard Feynman was an inspiring theoretical physicist whose work on path integrals, quantum electrodynamics, and nanotechnology reshaped our understanding of quantum mechanics. In his 1981 lecture "Simulating Physics with Computers," he argued that classical computers struggle to simulate quantum systems efficiently, suggesting nature might compute quantum mechanically. David Deutsch built on this in 1985 by formalizing the quantum Turing machine and showing quantum computers could solve problems intractable classically, such as factoring via later Shor's algorithm. Their emphasis on elegant structures, superposition, entanglement, and interference offers rich conceptual inspiration for clean, concise code.


Extra significant figures


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.



Playground V9


Playground V9 is the browser‑based Tcl/Tk console attached to the Tclers’ Wiki that lets you paste and run Tcl scripts interactively in a cloud session, without installing Tcl locally. It is used across “Snippets Physics Concepts” pages as the standard environment for short educational “toy” procs, with the constraint that all output must be strict ASCII.

To run the quantum‑circuit snippets there, a simple workflow is:

Open the Tclers’ Wiki page in a browser and use the “Playground” menu to launch a Tcl Playground V9 console in a separate tab or window.

Copy the entire tcl code block that defines quantum_circuit (and add any test circuits) from the wiki page, then paste it into the Playground console so that all proc definitions are loaded at once. Note: parsing, have to paste and copy code block onto the little clipboard tab, select all, windows copy to w. clipboard, and then use the paste command on the Playground headboard.

Extra Note. The clipboard tab on P9 is your only friend: Browser → little clipboard icon → select-all → Ctrl+C → headbar Paste button.

Press Enter to execute the pasted block; you should see any initial puts test messages confirming that the proc is defined and the console is working.

At the (tcl) prompt, paste the proc or deck with a circuit and qubit count parameters if needed, for example: print_quantum_circuit { {H 0} {S 0} {H 0} {M 0} } 1 ;# to render the phase‑kickback example on one qubit, or print_quantum_circuit { {H 0} {CNOT 0 1} } 2 ;# to see the Bell‑state circuit.

Caution: Beware the refresh button. It wipes the slate clean.

To experiment, edit the circuit list directly at the prompt (change gate order, add M gates, swap CNOT control/target) and re‑run the command; as long as you avoid non‑ASCII characters in any puts strings, Playground V9 will render the ASCII diagrams reliably.

Ultimate playground enlightenment: The fastest way to learn quantum gates is to break them in ASCII, what tap should have been right, and stare at the wreckage until it makes sense.

Note. Empty spaces are shown as dashed lines in printout, "\---".



Debugging tcl, What is that Chart on the QT, slang?


Debugging tcl. What is that Chart on the QT, slang? The chart reminds me of a gravity well, but you can tell me different?


Chart shows the elegance of the protocol and ideal boundaries, while exposing practical computing realities. Its V-shape tells a story of near-perfection punctuated by a numerical artifact, reinforcing that quantum teleportation QT achieves theoretical fidelity 1.0 in noiseless settings. The sustained high line across most cases illustrates universality. The method transfers any qubit state faithfully when resources are ideal. This visual reinforces the Tcl wiki's goal. The goal is providing accessible snippets for learning quantum concepts without heavy simulation overhead.


Real experiments report average fidelities around 0.80–0.90 over long distances (e.g., satellite links at 1,400 km) due to decoherence, photon loss, and detector noise—far from the ideal 1.0 shown here. The chart's near-perfect results after the dip remind users that deviations often stem from computation, not fundamental quantum limits.


Yes, the chart's shape does resemble a gravity well visualization in a striking way. And your observation is spot on. It's a fun and intuitive parallel even if the underlying causes are completely different. Classic gravity well diagrams often depict gravitational potential as a deep, funnel-like depression in a 2D surface. The gravity well visualizations are used in classrooms, science museums, or popular explanations of general relativity. A heavy object like a planet or star sits at the center, creating a smooth, curved dip that gets steeper near the middle. When viewed from the side or as a cross-section, this funnel frequently looks like a wide V or an inverted peak. There are high flat edges far away (where gravity is weak), sloping down sharply toward a central low point (maximum attraction at the object), and sometimes a flat or rounded bottom if the plot cuts off at the surface. Popular demos use stretched fabric (like spandex over a hoop) with a central weight to create this exact V-shaped valley in profile. Rolling marbles around the rim shows orbits or escapes. The simulation marbles are mimicking how objects need enough energy to climb out of the "well." Famous examples include the XXXX solar system gravity wells map (comparing depths across planets) or embedding diagrams for black holes, where the hyperbolic cross-section forms that iconic sudden central plunge.


The fidelity chart mirrors this visually in a simplified way. The line starts high (fidelity near 1.0 for the simple |0⟩ state), plunges to a low minimum at test case 2 (the approximate Hadamard superposition with rounded 0.7071 coefficients), then climbs steeply back up and levels off flat at perfect 1.0 for the exact cases. That V-shaped dip followed by a plateau echoes the gravity well's outer flats, steep walls, and central bottom—except inverted in meaning. In gravity, the bottom is the deepest trap (hardest to escape); here, the bottom is the "worst" fidelity (smallest overlap due to numerical error), while the high flats represent ideal performance. The resemblance is mostly coincidental and aesthetic, not physical or mathematical.


Debugging tcl, Need Tickets for Relativity?


Memo to Advisor. This Quantum Teleportation demo was published with a light-speed restriction, duly noted in debugging the Snippets. However, I’m told that Quantum Teleportation here is being considered for a star about 10.5 light-years away, in a Star Trek Pilot. If that Pilot succeeds, how would I independently check or debug the results beyond light speed? Are you selling two-way tickets for faster-than-light travel? Need to be back in time for Mama’s fried chicken supper. Joke!


From Advisor


Gist From Advisor: Quantum teleportation offers no shortcuts around the cosmic speed limit for usable information or people. Snippet provides perfect state transfer only when combined with sub-lightspeed classical signaling. Demo script beautifully illustrates the ideal mathematical fidelity, but real-world implementations face noise, loss, and the unbreakable light-speed barrier for the classical part.


Quantum teleportation never enables faster-than-light (FTL) communication or travel. The no-communication theorem in quantum mechanics proves that entanglement alone cannot transmit classical information instantaneously. Any attempt to use measurements on one side to signal the other fails because the local statistics remain unchanged until the classical message arrives. Independent verification would require waiting at least 10.5 years for any classical confirmation signal to reach Earth (plus another 10.5 years for a reply if two-way). You would check by receiving the classical correction bits, applying them to a local qubit, and measuring whether the reconstructed state matches the original one sent. Without those bits arriving via light-speed channels, no reconstruction occurs. No experiment could demonstrate "beyond light speed" effects because relativity forbids it for information transfer.


The Tcl code you shared is a clean, educational demonstration of quantum teleportation in its ideal (noiseless) form. The procedure teleport_fidelity takes the complex coefficients (alpha and beta) that describe an arbitrary single-qubit state to be teleported. In perfect quantum teleportation, the receiver (Bob) ends up with exactly the same state as the sender (Alice) started with. The code therefore sets Bob's coefficients to match Alice's input directly. It then computes the fidelity, which measures how close two quantum states are. Fidelity equals the square of the magnitude of the inner product between the input state and the output state. For identical states this inner product has magnitude 1, so fidelity is exactly 1.0. The small deviation you see for the approximate Hadamard state (0.7071 instead of exactly 1/sqrt(2) ≈ 0.707106781) arises from floating-point rounding in the input numbers. The other test cases use exact representable values, so they yield perfect 1.0 fidelity. This script confirms that, under ideal conditions with no decoherence or measurement errors, teleportation works flawlessly regardless of the input state.


Quantum teleportation transfers the quantum state of one particle to another distant particle using entanglement and classical communication. It requires three main steps. First, Alice and Bob share a pair of entangled particles (the Bell pair). Second, Alice performs a joint measurement (Bell-state measurement) on her qubit to teleport and her half of the entangled pair, obtaining two classical bits as the result. Third, Alice sends those two classical bits to Bob over a normal channel. Bob applies one of four possible corrections (Pauli X, Z, both, or neither) to his entangled qubit based on the bits received. After the correction, Bob's qubit holds exactly the original state Alice wanted to send. Importantly, no physical matter or energy travels faster than light. The entangled pair provides correlation, but the actual usable information arrives only after the classical bits travel at or below light speed. Without that classical message, Bob cannot reconstruct the state.


So, for now:


No two-way tickets beyond light speed — not even for dinner time! But hey, you can always say you’re testing relativity: “Sorry I’m late, Mama — time dilation!”


Gritty Details on Simon's Problem


Gist on Simon's Problem. This is a hacker's patch and not rigorously derived. Solution appears correct for equal amplitudes on non-zero entries. For s = 000, all eight basis states remain non‑zero after interference. So each amplitude is 1/8 and each probability is 1/8, giving a uniform distribution. For any non‑zero s, interference cancels half the states. This leaves exactly four non‑zero outcomes. Each of those gets amplitude 1/2 and probability 1/4, restricted to the y values satisfying y·s = 0. The “count the non‑zero amplitudes and assign amplitude 1/count” rule is just a compact way of expressing the same normalization that appears in the standard derivation of Simon’s problem.


This section explains the value of using clear, descriptive variable names in code, especially for educational quantum computing examples like Simon's algorithm. The purpose focuses on improving readability and understanding without changing program logic. Readers will see how meaningful names help students and developers grasp quantum interference concepts more easily in Tcl implementations. Human-readable names transform cryptic code into self-documenting material. Single-letter variables like x, y, or s force readers to track meanings through context or comments. In contrast, descriptive names immediately convey intent. For example, renaming s_bin to hidden_string_binary lets anyone see that the input represents the secret period string s in Simon's problem. This small change reduces mental effort. It allows focus on the physics rather than decoding abbreviations.


In quantum algorithms, interference plays a central role. Simon's algorithm uses quantum parallelism and destructive interference to hide outcomes where the dot product y · s equals 1 modulo 2. The code filters valid measurement outcomes correctly. However, names like valid_ys and amp_mag obscure this idea. Replacing them with states_orthogonal_to_hidden_string and uniform_amplitude_magnitude reveals the core mechanism. These states satisfy y · s = 0 (mod 2), so their amplitudes add constructively while others cancel due to phase opposition. Clear names highlight why certain probabilities become zero and others equal 1/k, where k counts the orthogonal subspace dimension.


The popcorncount procedure computes Hamming weight, the number of 1-bits. Its current name lacks connection to the task. A name like compute_hamming_weight or count_set_bits ties directly to bitwise operations used in the dot product check. Similarly, round_probs becomes format_probabilities_to_three_decimals. This name explains the formatting choice for console readability without needing extra comments. Such precision prevents misinterpretation in teaching settings.


Good naming follows consistent patterns and avoids one-letter shortcuts. The revised code keeps pure ASCII, stays concise, and uses snake_case for Tcl conventions. Descriptive names support the educational goal of showing interference in a toy n=3 case. Students see uniform distribution for s=000 and the characteristic 4 non-zero probabilities (each 0.250) for non-trivial s values. This clarity aids debugging and concept reinforcement.


In summary, adopting extremely descriptive names improves code quality dramatically. The changes remain minimal, preserving original logic while enhancing transparency. Developers and learners gain immediate insight into Simon's interference pattern, making the demonstration more effective for theoretical physics education.


Educational Applications


The program demonstrates quantum circuit 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 : 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" 


Screenshots Section



figure 1.


Snippets Physics Concepts Qubits screenshot Fidelity, from Playground V9


testing plot concept here, no frills


Snippets Physics Concepts Qubits screenshot Fidelity


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 Fixed Quantum Teleportation Demo


This is a draft, still debugging on Playground V9.



# Fixed Quantum Teleportation Demo V5
# Ideal case fidelity always 1.0
# 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/5/2026

console show
proc teleport_fidelity {alpha_real alpha_imag beta_real beta_imag} {
    # Input state: alpha|0> + beta|1>  (assume normalized: |alpha|^2 + |beta|^2 = 1)
    # In ideal teleportation, Bob's final qubit state matches input exactly
    set bob_alpha_real $alpha_real
    set bob_alpha_imag $alpha_imag
    set bob_beta_real  $beta_real
    set bob_beta_imag  $beta_imag
    # Fidelity = |<psi_input | psi_output>|^2 = 1 for perfect teleportation
    set overlap_real [expr {$alpha_real * $bob_alpha_real + $alpha_imag * $bob_alpha_imag + \
                            $beta_real  * $bob_beta_real  + $beta_imag  * $bob_beta_imag}]
    set overlap_imag [expr {$alpha_real * $bob_beta_imag  - $alpha_imag * $bob_beta_real + \
                            $beta_real  * $bob_alpha_imag  - $beta_imag  * $bob_alpha_real}]
    set fidelity [expr {$overlap_real**2 + $overlap_imag**2}]
    return [list "Bob state: $bob_alpha_real + $bob_alpha_imag i |0> + $bob_beta_real + $bob_beta_imag i |1>" \
                 "Fidelity: $fidelity (ideal = 1.0)"]
}
puts "Fixed Teleportation Fidelity Tests (ideal case):"
puts [teleport_fidelity 1.0 0.0  0.0 0.0]           ;# |0> input
puts [teleport_fidelity 0.7071 0.0  0.7071 0.0]     ;# (|0> + |1>)/sqrt(2)
puts [teleport_fidelity 0.8 0.0   0.6 0.0]          ;# 0.8|0> + 0.6|1> (real)
puts [teleport_fidelity 0.8 0.0   0.0 0.6]          ;# 0.8|0> + 0.6i|1>


Output from Playground V9



> }
(tcl) 2 % puts "Fixed Teleportation Fidelity Tests (ideal case):"
Fixed Teleportation Fidelity Tests (ideal case):
(tcl) 3 % puts [teleport_fidelity 1.0 0.0  0.0 0.0]           ;# |0> input
{Bob state: 1.0 + 0.0 i |0> + 0.0 + 0.0 i |1>} {Fidelity: 1.0 (ideal = 1.0)}
(tcl) 4 % puts [teleport_fidelity 0.7071 0.0  0.7071 0.0]     ;# (|0> + |1>)/sqrt(2)
{Bob state: 0.7071 + 0.0 i |0> + 0.7071 + 0.0 i |1>} {Fidelity: 0.9999616403678722 (ideal = 1.0)}
(tcl) 5 % puts [teleport_fidelity 0.8 0.0   0.6 0.0]          ;# 0.8|0> + 0.6|1> (real)
{Bob state: 0.8 + 0.0 i |0> + 0.6 + 0.0 i |1>} {Fidelity: 1.0 (ideal = 1.0)}
(tcl) 6 % puts [teleport_fidelity 0.8 0.0   0.0 0.6]          ;# 0.8|0> + 0.6i|1>
{Bob state: 0.8 + 0.0 i |0> + 0.0 + 0.6 i |1>} {Fidelity: 1.0 (ideal = 1.0)}
(tcl) 7 %


Output from ActiveState


Fixed Teleportation Fidelity Tests (ideal case):
{Bob state: 1.0 + 0.0 i |0> + 0.0 + 0.0 i |1>} {Fidelity: 1.0 (ideal = 1.0)}
{Bob state: 0.7071 + 0.0 i |0> + 0.7071 + 0.0 i |1>} {Fidelity: 0.9999616403678722 (ideal = 1.0)}
{Bob state: 0.8 + 0.0 i |0> + 0.6 + 0.0 i |1>} {Fidelity: 1.0 (ideal = 1.0)}
{Bob state: 0.8 + 0.0 i |0> + 0.0 + 0.6 i |1>} {Fidelity: 1.0 (ideal = 1.0)}
(bin) 1 % 

Toy Solver for Simon's Algorithm on Interference



# Simon's Algorithm on Interference Demo V5
# 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/5/2026

# this is a hacker's patch, not rigorously derived. 
# fixed factor
# appears correct for equal amplitudes
# pure ASCII code - no Unicode characters used anywhere

# Counts the number of 1-bits (Hamming weight) in a non-negative integer
proc count_set_bits {integer_value} {
    set value [expr {int($integer_value)}]
    set bit_count 0
    while {$value > 0} {
        incr bit_count [expr {$value & 1}]
        set value [expr {$value >> 1}]
    }
    return $bit_count
}

# Formats a list of probabilities to three decimal places for readable console output
proc format_probabilities_to_three_decimals {probability_list} {
    set formatted_values {}
    foreach probability $probability_list {
        lappend formatted_values [format "%.3f" $probability]
    }
    return $formatted_values
}

# Computes the probability distribution of measuring the second register
# in Simon's algorithm (n=3 qubits), given the hidden string s as a binary string
proc compute_measurement_probabilities_for_hidden_string {hidden_string_binary} {
    set hidden_string_integer 0b$hidden_string_binary
    
    # Collect all output states y (0 to 7) where the dot product y · s == 0 (mod 2)
    set states_orthogonal_to_hidden_string {}
    for {set output_state 0} {$output_state < 8} {incr output_state} {
        set and_result [expr {$output_state & $hidden_string_integer}]
        set dot_product_bit_count [count_set_bits $and_result]
        set dot_product_parity [expr {$dot_product_bit_count % 2}]
        if {$dot_product_parity == 0} {
            lappend states_orthogonal_to_hidden_string $output_state
        }
    }
    
    set number_of_orthogonal_states [llength $states_orthogonal_to_hidden_string]
    set uniform_amplitude_magnitude [expr {1.0 / sqrt($number_of_orthogonal_states)}]
    
    # Build the probability distribution:
    #   - states orthogonal to s receive equal probability 1 / number_of_orthogonal_states
    #   - all other states receive probability 0 due to destructive interference
    set probabilities {}
    for {set output_state 0} {$output_state < 8} {incr output_state} {
        if {$output_state in $states_orthogonal_to_hidden_string} {
            # In this simplified demonstration we assign positive real amplitude only
            # (phase choice does not change the observed probabilities |amp|^2)
            set probability [expr {$uniform_amplitude_magnitude ** 2}]
        } else {
            set probability 0.0
        }
        lappend probabilities $probability
    }
    
    set display_probabilities [format_probabilities_to_three_decimals $probabilities]
    return $display_probabilities
}

puts "Simon's algorithm demonstration (n=3 qubits)"
puts "Measurement probabilities in the second register after one query"
puts "to the quantum oracle (showing interference due to the hidden string s)\n"

puts "Case 1: hidden string s = 000   (trivial case - identity function)"
puts "   probabilities: [compute_measurement_probabilities_for_hidden_string 000]"
puts "   -> uniform distribution (~0.125 each) because every y is orthogonal to 000\n"

puts "Case 2: hidden string s = 011   (decimal 3)"
puts "   probabilities: [compute_measurement_probabilities_for_hidden_string 011]"
puts "   -> non-zero probability only for y where y dot 011 == 0 (mod 2)"
puts "     (exactly half the states survive constructive interference)\n"

puts "Case 3: hidden string s = 101   (decimal 5)"
puts "   probabilities: [compute_measurement_probabilities_for_hidden_string 101]"
puts "   -> non-zero probability only for y where y dot 101 == 0 (mod 2)"
puts "     (again exactly four states receive probability 0.250 each)\n"

puts "Notice: for any non-zero hidden string, exactly 2^(n-1) = 4 states"
puts "        have non-zero probability due to the structure of the subspace orthogonal to s."

Expected output


Simon's algorithm demonstration (n=3 qubits)
Measurement probabilities in the second register after one query
to the quantum oracle (showing interference due to the hidden string s)

Case 1: hidden string s = 000   (trivial case - identity function)
   probabilities: 0.125 0.125 0.125 0.125 0.125 0.125 0.125 0.125
   -> uniform distribution (~0.125 each) because every y is orthogonal to 000

Case 2: hidden string s = 011   (decimal 3)
   probabilities: 0.250 0.000 0.000 0.250 0.250 0.000 0.000 0.250
   -> non-zero probability only for y where y dot 011 == 0 (mod 2)
     (exactly half the states survive constructive interference)

Case 3: hidden string s = 101   (decimal 5)
   probabilities: 0.250 0.000 0.250 0.000 0.000 0.250 0.000 0.250
   -> non-zero probability only for y where y dot 101 == 0 (mod 2)
     (again exactly four states receive probability 0.250 each)

Notice: for any non-zero hidden string, exactly 2^(n-1) = 4 states
        have non-zero probability due to the structure of the subspace orthogonal to s.
#
#
# conclusion, another simplified  try???, 2/6/2026):
Simon's n=3 Tests:
s=000 (1-to-1): probs 0.125 0.125 0.125 0.125 0.125 0.125 0.125 0.125 ;# uniform 0.125 each
s=011 (period 3): probs 0.25 0.0 0.0 0.25 0.25 0.0 0.0 0.25 ;# non-zero only for y·011=0
s=101 (period 5): probs 0.25 0.0 0.25 0.0 0.0 0.25 0.0 0.25
# Check Sum of non-zero probs equals 1, true or not?

Output from Playground V9



# this is a hacker's patch, not rigorously derived. 
# fixed factor
# appears correct for equal amplitudes
> }
(tcl) 9 % 
(tcl) 9 % puts "Simon's algorithm demonstration (n=3 qubits)"
Simon's algorithm demonstration (n=3 qubits)
(tcl) 10 % puts "Measurement probabilities in the second register after one query"
Measurement probabilities in the second register after one query
(tcl) 11 % puts "to the quantum oracle (showing interference due to the hidden string s)\n"
to the quantum oracle (showing interference due to the hidden string s)

(tcl) 12 % 
(tcl) 12 % puts "Case 1: hidden string s = 000   (trivial case - identity function)"
Case 1: hidden string s = 000   (trivial case - identity function)
(tcl) 13 % puts "   probabilities: [compute_measurement_probabilities_for_hidden_string 000]"
   probabilities: 0.125 0.125 0.125 0.125 0.125 0.125 0.125 0.125
(tcl) 14 % puts "   -> uniform distribution (~0.125 each) because every y is orthogonal to 000\n"
   -> uniform distribution (~0.125 each) because every y is orthogonal to 000

(tcl) 15 % 
(tcl) 15 % puts "Case 2: hidden string s = 011   (decimal 3)"
Case 2: hidden string s = 011   (decimal 3)
(tcl) 16 % puts "   probabilities: [compute_measurement_probabilities_for_hidden_string 011]"
   probabilities: 0.250 0.000 0.000 0.250 0.250 0.000 0.000 0.250
(tcl) 17 % puts "   -> non-zero probability only for y where y dot 011 == 0 (mod 2)"
   -> non-zero probability only for y where y dot 011 == 0 (mod 2)
(tcl) 18 % puts "     (exactly half the states survive constructive interference)\n"
     (exactly half the states survive constructive interference)

(tcl) 19 % 
(tcl) 19 % puts "Case 3: hidden string s = 101   (decimal 5)"
Case 3: hidden string s = 101   (decimal 5)
(tcl) 20 % puts "   probabilities: [compute_measurement_probabilities_for_hidden_string 101]"
   probabilities: 0.250 0.000 0.250 0.000 0.000 0.250 0.000 0.250
(tcl) 21 % puts "   -> non-zero probability only for y where y dot 101 == 0 (mod 2)"
   -> non-zero probability only for y where y dot 101 == 0 (mod 2)
(tcl) 22 % puts "     (again exactly four states receive probability 0.250 each)\n"
     (again exactly four states receive probability 0.250 each)

(tcl) 23 % 
(tcl) 23 % puts "Notice: for any non-zero hidden string, exactly 2^(n-1) = 4 states"
Notice: for any non-zero hidden string, exactly 2^(n-1) = 4 states
(tcl) 24 % puts "        have non-zero probability due to the structure of the subspace orthogonal to s."
        have non-zero probability due to the structure of the subspace orthogonal to s.
(tcl) 25 % 


Output from ActiveState


# appears correct for equal amplitudes
Simon's n=3 Tests:
s=000 (1-to-1): probs 0.125 0.125 0.125 0.125 0.125 0.125 0.125 0.125 ;# uniform ~0.125 each
s=011 (period 3): probs 0.250 0.000 0.000 0.250 0.250 0.000 0.000 0.250 ;# non-zero only for y·011=0
s=101 (period 5): probs 0.250 0.000 0.250 0.000 0.000 0.250 0.000 0.250
(Documents) 1 % 
(bin) 1 % 

Deutsch-Jozsa Core Interference


console show
# Deutsch-Jozsa core interference for n=2: check amplitude at |00> after H-U_f-H
proc dj_interference {phases} {
    # phases: list of (-1)^f(x) for x=00,01,10,11
    set sum 0.0
    foreach p $phases { set sum [expr {$sum + $p}] }
    set amp00 [expr {$sum / 4.0}]
    set prob00 [expr {$amp00 ** 2}]
    return [list $amp00 $prob00]
}
puts "DJ n=2 Tests:"
set r [dj_interference {1 1 1 1}];   puts "Constant 0: amp00=[lindex $r 0] prob=[lindex $r 1]"
set r [dj_interference {-1 -1 -1 -1}]; puts "Constant 1: amp00=[lindex $r 0] prob=[lindex $r 1]"
set r [dj_interference {1 1 -1 -1}]; puts "Balanced:   amp00=[lindex $r 0] prob=[lindex $r 1]"


Output from Playground V9



(tcl) 3 % puts "DJ n=2 Tests:"
DJ n=2 Tests:
(tcl) 4 % set r [dj_interference {1 1 1 1}];   puts "Constant 0: amp00=[lindex $r 0] prob=[lindex $r 1]"
Constant 0: amp00=1.0 prob=1.0
(tcl) 5 % set r [dj_interference {-1 -1 -1 -1}]; puts "Constant 1: amp00=[lindex $r 0] prob=[lindex $r 1]"
Constant 1: amp00=-1.0 prob=1.0
(tcl) 6 % set r [dj_interference {1 1 -1 -1}]; puts "Balanced:   amp00=[lindex $r 0] prob=[lindex $r 1]"
Balanced:   amp00=0.0 prob=0.0
(tcl) 7 % 

Output from ActiveState


DJ n=2 Tests:
Constant 0: amp00=1.0 prob=1.0
Constant 1: amp00=-1.0 prob=1.0
Balanced:   amp00=0.0 prob=0.0
(bin) 1 % 


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



----
[gold] 2/6/2026.   fixing Simon's Algorithm , incorrect normalization factor of 1/√4 instead of 1/√8. also logic  bug, on parity check.
        set amp [expr {$parity == 0 ? 1.0/sqrt(8.0) : 0.0}] ;# key logic bug here
        # "set amp " giving wrong answers for examples 2 and 3


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.