Thomas Ehmer

Thomas Ehmer

Programming a Quantum - I-Ging, a showcase

The initial thought of what could make the Entangled Health podcast interesting …

Thomas Ehmer's avatar
Thomas Ehmer
Feb 16, 2026
∙ Paid

This is going to be a mix of tutorial how (and why!) to program a quantum computer, using LLMs to help the initial thought mature, and some look behind the scenes at the very end when it comes to the Podcast and ways to run it.

Note: this might be long and too big for the email text, so if you read it as email, maybe you land here on the web page.

Image: visualization of a Quantum “algorithm”

What you see above is the maybe shortest algorithm you can build on a quantum computer - like the one I am using for my private purpose, which is the IBM Platform, where you can get a free account and play with it - I have it for traditional reasons because I started there maybe few weeks after it first was making available to the public nearly ten years back somewhen in 2016.

With this article, we follow my thinking process along the journey of the Quantum I-Ging - improved - and the steps for using it as “question pool picker” for Entangled Health - at least in some of the early episodes.

The first step is analysing the initial euphoria, there will be more questions later, but let’s start with the basics.

Basic Questions to ask:

  • What are current quantum computers good at?

  • What is the I Ging (or I-Ching) and what has this to do with the story?

  • What are gates and which gates to use?

  • How many qubits?

  • How do I translate probabilities to gates

  • How do I mimic the REAL process of “divination” as realistic as possible

  • So what - I have more than 64 Questions in the Pool …

  • How to use an LLM to optimize the code

Let’s go step by step, this is my personal view, and there are many alternative ways, I tell you mine - used in this specific case. But before we go with the first block, here a preview of what lays ahead …


Follow-up questions:

  • Do you need to set an intention for the I-Ging to get guidance?

  • What about state preparation to reflect the “cosmic context”?

  • How do you encode your intention?

  • Does this make sense? At all?


Even more follow-up questions:

  • Do I have a good example how the QRNG picked an interesting question?

  • Could I have achieved that without QRNG?

  • What would I expect from the I-Ching approach?

  • Do I need a random question at all?

  • What alternatives exist?


Let’s start with the basic questions.

What are current quantum computers good at?

Good question. Some of you are inside the industry, so you know this question is part of a joke and friendly debate. For those of you not working daily with computers in general and quantum in special, here a brief intro, very casual, but correct. (Yes I know what I write).

There are different flavors of Quantum Computers, and most of them use the concept of a “Qubit” - which is in principle a mathematical construct which allows something we call “superposition”, where the coefficients are complex numbers and the |0> and |1> are states, and by that allows you to move away from the classical “Bit” (which is always TRUE or FALSE, there is no undefined state.)

Classical Bit: b = 0 OR b = 1  
this bit is always on one definite State TRUE (1) or FALSE (0)

Qubit: |q> = alpha |0> + beta |1> - with alpha^2 + beta^2 = 1
You can prepare the Qubit (and set alpha and beta so that it satisfies the boundary), and then your Qubit |q> is in this state. 
The alpha and beta relate to the PROBABILITY that once you measure it that you get |0> or |1>.  

Long story short, you can mix it so that it encodes what you need, and once you MEASURE the Qubit at the end, it “collapes” to one (only one) of the so-called Basis-state - either |0> or |1>. The clever part is that the alpha and beta somewhat correspond to the probability of getting into one of the states (more maths later, promised!).

Are you following? There are good tutorials everywhere, but this should be enough for here - this article is NOT about a detailed introduction. I even wrote one myself here in a chapter for Wiley.

The physics is tricky, you use either real physical things, like neutral Atoms or then charged Ions or electrons or other spins like Nitrogen Vacancies — or you use photons, then a bit of a different concept - or you generate artificial ones, like a SQUID or other concepts. The linked papers are where I contributed, of course there are 100s of others, but at least these I know in detail.

All of these “modalities” have their pros and cons, what they all have in common is that they are fragile and MUST NOT interact with the environment, because in the moment you have the system interact, you “measure” it which destroys the superposition. (Side note: in reality you also have a relative phase, which makes things more complex (also in the literal sense!) but we can ignore that here.)

Currently lot of effort is going on to make these things stable and NOT interact with the environment.

So what Quantum computers are good at is: generate a state that once you measure it, gives you a defined probability distribution, say 25% |0> and 75% |1>.

Can you do that classically? Yes of course.

The quantum Bonus: Each measurement is pure chance. You specify the the target distribution, and over millions of measurements you will get it, but the single measurement is a REAL random sample out of that distribution.

Can you do that classically? Nope. Not with a classical digital computer.


What is the I Ging (or I-Ching) and what has this to do with the story?

The I Ching (易經, Yìjīng), or “Book of Changes,” is one of the oldest divination systems in the world and among the most ancient books still in use. At its core, it’s a philosophical and cosmological text that uses 64 hexagrams, which are six-line figures composed of solid (Yang —) and broken (Yin - -) lines. The idea is that these represent all possible states of change and transformation in the universe.

The system is built on the fundamental Chinese concept of Yin and Yang, representing complementary opposites (dark/light, receptive/creative, feminine/masculine) that combine into eight trigrams, which further combine into 64 hexagrams.

Maybe best read more on wiki. But here a bit of extracted info - because it’s always fun to learn stuff.

Origin and Intent

Historical Development
The I Ching evolved through several distinct phases:

  • Shang Dynasty (1600-1046 BCE): The earliest forms emerged from oracle bone divination, where diviners applied heat to turtle shells or ox bones and interpreted the resulting cracks.

  • Western Zhou Period (1000-750 BCE): The text crystallized as a divination manual. Tradition credits King Wen of Zhou with creating the hexagram sequence and judgments while imprisoned, and his son, the Duke of Zhou, with authoring the line texts.

  • Warring States Period (500-200 BCE): The work transformed from pure divination into a cosmological and philosophical text, with the addition of the “Ten Wings”, i.e. commentaries attributed (likely incorrectly) to Confucius.

  • 2nd Century BCE: It became one of the Five Classics of Chinese literature and the foundation for divination practice across East Asia for millennia.

Original Intent
Chinese emperors and leaders consulted it for high-stakes political and military decisions for thousands of years, and imperial examinations required deep I Ching knowledge, so the I Ching served multiple purposes:

  1. Divination and Decision-Making: Consulting the oracle on matters of state, war, alliances, marriage, and personal affairs

  2. Philosophical Framework: Understanding the nature of change, balance, and harmony with the Tao

  3. Moral Guidance: Providing ethical counsel on proper conduct and governance

  4. Cosmological Understanding: Mapping the structure of reality through Yin-Yang dynamics

If you are curious, there are different ways to get to the texts (of course internet), but also classical books.

Resources to Obtain the I Ching

There are two flavors, the “classic” translations of the original texts, and the “modern” adaptions.

Classic Translations:

  • Richard Wilhelm/Cary Baynes (1950): The most influential Western translation, featuring Carl Jung’s famous introduction explaining synchronicity and the psychological dimensions of the oracle

  • James Legge Translation: Earlier scholarly translation

  • Alfred Huang’s Complete I Ching: Modern, comprehensive version

Modern Adaptations are apps and online versions (I sometimes use the orakel.net version in german) for digital consultation, simplified guides for beginners and even “Business-focused” interpretations. You find them quickly if you look wherever you prefer to look.

As side note for Further Reading: Journey to the West (or “the yellow book, my paperback edition has some 1300 pages and is actually yellow).

While the I Ching (1000 BCE) and Journey to the West (1592 CE) are separated by 2,500 years, the epic tale of Sun Wukong - or the Monkey King - serves as a narrative companion to the oracle’s philosophy of transformation. The novel’s 81 trials mirror the I Ching’s cycles of change, with Sun Wukong embodying the “monkey mind” that must learn to flow with change rather than rebel against it, moving from chaos (pure Yang) through balance to enlightenment.

If you are like me, i.e. for those of you seeking to understand the I Ching’s abstract hexagrams through story, Journey to the West offers the same Daoist and Buddhist wisdom wrapped in an adventure of a rebellious immortal ape learning what the oracle teaches: that true power comes not from forcing outcomes, but from harmonizing with the eternal dance of Yin and Yang. Note: It is a really long read. And thanks goes to Paul Werbos here who brought it to my attention in the first place.

Ok, now back to quantum.


What are gates and which gates to use?

You remember the qubits from above, right? In principle they can be imagined as a vector, or a pointer pointing to a specific point on the surface of a sphere. (the Bloch sphere), where |0> is North pole, and |1> the South pole. I have made this illustration where you see what we try to do. We want to take the original red arrow - pointing to the North, to point it to somewhere on the equator (the green arrow). Means you rotate the arrow.

Sometimes I joke and say quantum computing is like aiming with a Death Star.

The arrows are quantum states (in the easiest case, one qubit), and are written often described with the letter psi - means |ψ>

In gate based quantum computing, you do this by introducing rotational gates, which are more or less the instruction what happens to the arrow, in mathematical terms this is linear algebra and Matrix Multiplication. You can look that up if you want but I spare you the details here.

A bloch sphere (left) illustration two qubits, the red one points to the state |0> and the green one somewhere to the equator, a superposition of |0> and |1>, in this case selected to be 50/50. (Credit: Thomas Ehmer, the figure is also published in my Wiley Book article)

There are several one-qubit Gates, which means they rotate the arrow of one Bloch sphere. Typically you can rotate in three dimensions and about any angle, typically taken around the x-, y- or z- axis.

As you can see, we are on a sphere, which means three dimensions, which also means two angles, phi (φ) and theta (ϑ or also written as θ ) and your rotation gates are matrix multiplications where in the end you multiply the arrow vector. Here is your math:

\(\begin{gather} |\psi\rangle = \alpha |0\rangle + \beta |1\rangle \text{, with } |\alpha|^{2} + |\beta|^{2}=1 \\ \alpha = \cos\frac{\vartheta}{2}, \text{ and } \beta = e^{i\phi}\sin\frac{\vartheta}{2}\\ \text{ where } \phi \in [0, 2\pi] \text{ and } \vartheta \in [0, \pi] \\ \\ \text{and (just a hint - not to to confuse you there are two ways to write theta ) } \theta = \vartheta \end{gather} \)

So if you want to rotate that thing in the most flexible way, using linear algebra, this is how it looks, it is a unitary Transformation” (which means in principle that it is reversible and nothing is broken) and called U3 for a good reason. You will notice a λ (lambda), which is a Global phase angle (0 to 2π) - as an additional phase, but we do not need that, typically it is ignored.

\(U_3(\theta, \varphi, \lambda) = \begin{pmatrix} \cos\frac{\theta}{2} & -e^{i\lambda}\sin\frac{\theta}{2} \\ e^{i\varphi}\sin\frac{\theta}{2} & e^{i(\varphi+\lambda)}\cos\frac{\theta}{2} \end{pmatrix}\)

We can now decide to rotate only along one axis, let’s say y-axis, which is the theta angle, and have specific one qubit rotation gates, e.g. the Ry gate, which looks like this.

\(R_Y(\theta) = \begin{pmatrix} \cos\frac{\theta}{2} & -\sin\frac{\theta}{2} \\ \sin\frac{\theta}{2} & \cos\frac{\theta}{2} \end{pmatrix} \)

Now, as we want to construct probability distributions for one thing at a time, and those are not influencing each other (!), we do not need all the quantum computing magic like entanglement, which actually would be used, because it makes one qubit dependent on the other.

We can skip the details of two-qubit gates - and maybe refer to an article in the future, or if you want to learn it, check out the existing tutorials, which are good, and available for free. In principle the Matrix gets bigger (2x2 for one qubit, 4x4 for two qubits, 8x8 for three and so on).

\(\begin{aligned} &\text{3 qubits} \quad \Rightarrow \quad 2^3 = 8 \text{ computational basis states:} \\[6pt] &\{|000\rangle, |001\rangle, |010\rangle, |011\rangle, \\[4pt] &\phantom{\{} |100\rangle, |101\rangle, |110\rangle, |111\rangle\} \end{aligned} \)

You see the magic of computational power comes by entangling the qubits, because you can encode exponentially more information in a qubit than you can in a classical bit.

\( \text{General case:} \quad n \text{ qubits} \quad \Rightarrow \quad 2^n \text{ states} \)

How many qubits?

For the I-Ging case, you see that it is a hexagram, means six lines.

Now depending on the process, we can either work with six qubits, or six times one.

Let’s see, and I was playing with the approaches, so it’s a good question, and there is no real answer.


How do I translate probabilities to gates?

As we have seen above, you rotate the qubit from the initial state |0>, that’s what all quantum computer do in the beginning, with a specific gate to a state where the probabilities result in what you need. We have seen the obvious above, 50:50 for the equator.

In the case of the I-Ging, there are several probabilities, resulting from the process of divination. Let’s just say, if you need to implement a specific probability, you can calculate it with the formulas above, you need in the end to determine the angle, let’s take a sneak peak and try to implement a probability of 3:1 - means 75% and 25% - We will see later why this is, but let’s agree that for the first step of the yarrow stalk divination method (see later below), we need to generate a random outcome with a 3:1 probability ratio:

  • Value 2: P(0) = 1/4 = 25%

  • Value 3: P(1) = 3/4 = 75%

How do we create this unequal probability split using a quantum circuit?

We use an Ry rotation gate that rotates a qubit around the Y-axis of the Bloch sphere. Look again at the Ry form above.

When applied to the initial state |0⟩:

Ry(θ)|0⟩ = cos(θ/2)|0⟩ + sin(θ/2)|1⟩

But How do we get the angle?

Mathematics, - we all love it, right?

To achieve our 3:1 ratio, we need the quantum state:

|ψ⟩ = (1/2)|0⟩ + (√3/2)|1⟩

Why these specific amplitudes? Because - you recall from above - quantum measurement probabilities are the square of amplitudes:

  • P(0) = |1/2|² = 1/4

  • P(1) = |√3/2|² = 3/4

Now we match this to the Ry gate output:

  • cos(θ/2) = 1/2

  • sin(θ/2) = √3/2

From the sine equation:

sin(θ/2) = √3/2

Taking the inverse sine:

θ/2 = arcsin(√3/2) = π/3 = 60°

Therefore:

θ = 2π/3 = 120° ≈ 2.0944 radians

Verification (duh…)

Let’s verify this produces the correct probabilities:

P(|0⟩) = cos²(60°) = (1/2)² = 1/4 ✓

P(|1⟩) = sin²(60°) = (√3/2)² = 3/4 ✓

Ratio: 3/4 : 1/4 = 3:1 ✓

Perfect!

But why 3:1 - and what IS the process of the I-Ging Divination?

This 3:1 split in the first step of yarrow stalk division is crucial. When combined with two additional 1:1 splits (using Hadamard gates), it produces the authentic probability distribution for the four line types:

  • Old Yin (6): 1/16 = 6.25%

  • Young Yang (7): 5/16 = 31.25%

  • Young Yin (8): 7/16 = 43.75%

  • Old Yang (9): 3/16 = 18.75%


How do I mimic the REAL process of “divination” as realistic as possible ?

Let’s first check the options of the “Divination Processes”, and we note these result in different possiblities. For whatever reasons, the Inventors of I-Ging used the values 2 and 3, and then took three iterations to come up with the sum (6, 7, 8, 9) and these represent the final lines (Yin / Yang) either (Old / Young).

Yarrow Stalk Method (Traditional)

The most authentic and complex method, the process is:The Real Classical Yarrow Stalk Method (from Wilhelm’s I Ching)

You sum the numerical values assigned to the remainders from the three rounds.​

Each Round:

  1. Divide 49 stalks randomly into two piles

  2. Take 1 stalk from right pile (place between ring & little finger)

  3. Count left pile by 4s until 1-4 remain

  4. Count right pile by 4s until 1-4 remain

  5. The remainders between your fingers total either 5 or 9 (round 1) or 4 or 8 (rounds 2-3)​

Converting Remainders to Values

Round 1:

  • 9 remainders → value of 2

  • 5 remainders → value of 3​

Rounds 2 & 3:

  • 8 remainders → value of 2

  • 4 remainders → value of 3​

Getting the Final Line Value

  1. Sum the three values to get the line type: 6 (Old Yin, changing), 7 (Young Yang), 8 (Young Yin), or 9 (Old Yang, changing)

  2. Build six lines from bottom to top to create a hexagram

Probabilities:

  • Old Yin (6): 1/16 (6.25%)

  • Young Yang (7): 5/16 (43.75%)

  • Young Yin (8): 7/16 (43.75%)

  • Old Yang (9): 3/16 (18.75%)

This method takes 15-20 minutes and is considered meditative. fun fact, it runs approximately the same amount of time on a quantum computer, due to repeated state preparation.

And you see we have even more un-even probability distributions, bear with me, I had the same question HOW on Earth would I implement that with rotational gates!

YARROW STALK METHOD QUICK REFERENCE

Initial Setup:
• 50 stalks → Remove 1 → Work with 49

Each Round (do 3 times per line):
1. Divide 49 (or remaining) into two random piles
2. Take 1 from right pile (between fingers)
3. Count left pile by 4s (1-4 remain)
4. Count right pile by 4s (1-4 remain)
5. Total remainders between fingers

Remainder → Value Conversion:
Round 1: 9→2, 5→3
Round 2: 8→2, 4→3
Round 3: 8→2, 4→3

Final Line Value:
Sum of 3 values → 6, 7, 8, or 9

Complete Hexagram:
Repeat 6 times (bottom to top)

Coin Method (Simplified)

A faster alternative using three coins, here the Process is:

  • Assign values: Heads = 3, Tails = 2

  • Toss three coins

  • Sum the values:

    • 9 (3 heads): Old Yang (changing) - 1/8 (12.5%)

    • 8 (2 heads, 1 tail): Young Yin - 3/8 (37.5%)

    • 7 (1 head, 2 tails): Young Yang - 3/8 (37.5%)

    • 6 (3 tails): Old Yin (changing) - 1/8 (12.5%)

  • Repeat six times for six lines

Note: Both methods produce changing (Old) lines with 1/4 probability, but the coin method treats Old Yang and Old Yin equally (1:1 ratio), while the yarrow method favors Old Yang over Old Yin (3:1 ratio), creating a more yang-biased dynamic in readings.

OK. Now, how do we get this formulated so that we can implement it in code, let’S go with the traditional method.

Step 1 (3:1 ratio):

  • Value 2: P = 1/4

  • Value 3: P = 3/4

Step 2 (1:1 ratio):

  • Value 2: P = 1/2

  • Value 3: P = 1/2

Step 3 (1:1 ratio):

  • Value 2: P = 1/2

  • Value 3: P = 1/2

(Step1, Step2, Step3) → Sum | Probability
─────────────────────────────────────────
(2, 2, 2) → 6 | 1/4 × 1/2 × 1/2 = 1/16
(2, 2, 3) → 7 | 1/4 × 1/2 × 1/2 = 1/16
(2, 3, 2) → 7 | 1/4 × 1/2 × 1/2 = 1/16
(2, 3, 3) → 8 | 1/4 × 1/2 × 1/2 = 1/16
(3, 2, 2) → 7 | 3/4 × 1/2 × 1/2 = 3/16 ← Step 1 gives 3×
(3, 2, 3) → 8 | 3/4 × 1/2 × 1/2 = 3/16
(3, 3, 2) → 8 | 3/4 × 1/2 × 1/2 = 3/16
(3, 3, 3) → 9 | 3/4 × 1/2 × 1/2 = 3/16

Grouping by Sum

Sum = 6 (Old Yin): 1 way

  • Total: 1/16 = 6.25%

Sum = 7 (Young Yang): 3 ways

  • Total: 1/16 + 1/16 + 3/16 = 5/16 = 31.25%

Sum = 8 (Young Yin): 3 ways

  • Total: 1/16 + 3/16 + 3/16 = 7/16 = 43.75%

Sum = 9 (Old Yang): 1 way

  • Total: 3/16 = 18.75%

Image: A diagram of I Ching hexagrams sent to Leibniz from Joachim Bouvet. The Arabic numerals were added by Leibniz - that’s what wiki said.

Apparently, this discovering and working with the I Ging inspired Leibnitz to invent the binary system and calculus machines. (see there also a nice chapter in the book “On the shoulders of giants” from Brian Lenahan and Kenna Hughes-Castleberry - I mention it here because it’s a good book, a different perspective on quantum mechanics, and Kenna interviewed me for the chapter ((-; )

Getting ready to code? One more thing …


Two Paths to Quantum Divination: Implementing the Yarrow Stalk Method

When building a quantum I Ging oracle, we face a fundamental design choice: should we directly encode the target probabilities into quantum gates, or simulate the physical yarrow stalk process itself? Both approaches produce mathematically identical results, but they represent different philosophies of quantum implementation.

The Rotation Method: Pure Probability

The first approach treats the yarrow stalk method as a probability problem. We know the desired outcome: Step 1 needs a 3:1 ratio, Steps 2 and 3 need 1:1 ratios. The elegant solution? Encode these probabilities directly into quantum gates.

For the 3:1 ratio in Step 1, we use an RY rotation gate. The mathematics are straightforward: we want a quantum state where measuring |1⟩ has 75% probability and |0⟩ has 25% probability. This requires:

|ψ⟩ = (1/2)|0⟩ + (√3/2)|1⟩

The rotation angle that creates this state is θ = 2π/3 (120 degrees). For Steps 2 and 3, a simple Hadamard gate creates perfect 50/50 superposition.

Rotation Method Code

import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator

# Initialize backend once (outside function)
backend = AerSimulator()

def create_yarrow_step_circuit(step_num: int) -> QuantumCircuit:
    """Create quantum circuit for one yarrow stalk step."""
    qc = QuantumCircuit(1, 1)
    
    if step_num == 1:
        # Step 1: 3:1 ratio (75% for |1⟩, 25% for |0⟩)
        theta = 2 * np.arcsin(np.sqrt(3/4))  # 2.0944 radians
        qc.ry(theta, 0)
    else:
        # Steps 2-3: 1:1 ratio (50% each)
        qc.h(0)
    
    qc.measure(0, 0)
    return qc

def generate_iching_line_rotation() -> int:
    """Generate one I Ching line using rotation method."""
    step_values = []
    
    for step in range(1, 4):
        qc = create_yarrow_step_circuit(step)
        
        # Transpile circuit for backend
        transpiled_qc = transpile(qc, backend)
        
        # Execute circuit
        job = backend.run(transpiled_qc, shots=1)
        result = job.result()
        counts = result.get_counts()
        
        # Convert measurement to value (0→2, 1→3)
        measurement = int(list(counts.keys())[0])
        value = 2 if measurement == 0 else 3
        step_values.append(value)
    
    # Sum to get line value (6, 7, 8, or 9)
    return sum(step_values)

# Test
for i in range(3):
    line = generate_iching_line_rotation()
    line_type = {6: "Old Yin", 7: "Young Yang", 8: "Young Yin", 9: "Old Yang"}
    print(f"Line {i+1}: {line} ({line_type[line]})")

This method is fast, elegant, and efficient. It uses minimal quantum resources, just one qubit per step, and produces results in milliseconds. For production systems running on real quantum hardware, this is the optimal choice.

The Real Stalk Method: Physical Simulation

The second approach takes a radically different philosophy: simulate the actual physical process. Instead of encoding target probabilities, we recreate the traditional yarrow stalk procedure using quantum randomness to split piles and count remainders.

This method tracks 49 stalks through three rounds of division. In each round, we use quantum superposition to randomly split the stalks into two piles, then calculate remainders by counting groups of four—exactly as you would with physical stalks.

Real Stalk Method Code

import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from typing import Tuple, Dict, List

class QuantumYarrowRealStalk:
    """Quantum I Ching oracle using real stalk simulation method."""
    
    def __init__(self):
        """Initialize the oracle with quantum backend."""
        self.backend = AerSimulator()
    
    def _quantum_random_split(self, total_stalks: int, min_per_pile: int = 1) -> int:
        """Use quantum randomness to split stalks into two piles."""
        max_value = total_stalks - min_per_pile
        num_qubits = int(np.ceil(np.log2(max_value - min_per_pile + 1)))
        
        if num_qubits == 0:
            return min_per_pile
        
        qc = QuantumCircuit(num_qubits, num_qubits)
        
        for i in range(num_qubits):
            qc.h(i)
        
        qc.measure(range(num_qubits), range(num_qubits))
        
        try:
            transpiled_qc = transpile(qc, self.backend)
            job = self.backend.run(transpiled_qc, shots=1)
            result = job.result()
            counts = result.get_counts()
            
            bitstring = list(counts.keys())[0]
            value = int(bitstring, 2)
            right_pile = min_per_pile + (value % (max_value - min_per_pile + 1))
            
            return right_pile
            
        except Exception as e:
            import secrets
            return secrets.randbelow(max_value - min_per_pile + 1) + min_per_pile
    
    def _yarrow_division_step(self, num_stalks: int, step_num: int) -> Tuple[int, int]:
        """Perform one yarrow stalk division step."""
        right_pile = self._quantum_random_split(num_stalks)
        left_pile = num_stalks - right_pile
        
        right_pile -= 1
        observer_stalk = 1
        
        left_remainder = (left_pile % 4) or 4
        right_remainder = (right_pile % 4) or 4
        
        stalks_removed = left_remainder + right_remainder + observer_stalk
        
        if step_num == 1:
            value = 3 if stalks_removed == 5 else 2
        else:
            value = 3 if stalks_removed == 4 else 2
        
        return value, stalks_removed
    
    def generate_line(self) -> Dict:
        """Generate one I Ching line with detailed information."""
        stalks_remaining = 49
        step_values = []
        step_details = []
        
        for step_num in range(1, 4):
            value, removed = self._yarrow_division_step(stalks_remaining, step_num)
            step_values.append(value)
            step_details.append({
                'step': step_num,
                'stalks_before': stalks_remaining,
                'value': value,
                'removed': removed
            })
            stalks_remaining -= removed
        
        line_value = sum(step_values)
        
        line_types = {
            6: "Old Yin (changing)",
            7: "Young Yang (stable)",
            8: "Young Yin (stable)",
            9: "Old Yang (changing)"
        }
        
        return {
            'value': line_value,
            'type': line_types[line_value],
            'is_changing': line_value in [6, 9],
            'step_details': step_details
        }
    
    def generate_hexagram(self, verbose: bool = False) -> Dict:
        """Generate complete hexagram."""
        lines = []
        
        for position in range(1, 7):
            line = self.generate_line()
            line['position'] = position
            lines.append(line)
            
            if verbose:
                print(f"Line {position}: {line['value']} - {line['type']}")
        
        return {
            'lines': lines,
            'has_changing_lines': any(line['is_changing'] for line in lines)
        }

# Usage
oracle = QuantumYarrowRealStalk()
hexagram = oracle.generate_hexagram(verbose=True)

This method requires more quantum resources, namely up to 6 qubits per split to handle the range of possible pile sizes. It’s slower and more complex, but it offers something the rotation method cannot: a direct connection to the ancient ritual.

Choosing Your Path

Both methods produce identical probability distributions:

  • Old Yin (6): 1/16 = 6.25%

  • Young Yang (7): 5/16 = 31.25%

  • Young Yin (8): 7/16 = 43.75%

  • Old Yang (9): 3/16 = 18.75%

The rotation method is ideal for production systems, real quantum hardware, and applications where speed matters. The real stalk method shines in educational contexts, demonstrations, and situations where honoring the traditional process adds meaning.


So what - I have more than 64 Questions in the Pool …

add more qubits , or do more iterations.


How to use an LLM to optimize the code ?

You have been waiting for that, right? So the quick answer is: go to Perplexity or whatever, select the model of choice (I use Claude 4.5) - prompt “this is not optimal code, simplify it for me and explain what you did” and then copy-paste your code.

Easy as that. Does it work? Yes. Cost maybe 20 bucks a month for the reliable use of the good models - sometimes even free, unless you go premium and buy the best of the best - which I don’t.

If we want we can replace the “optimize” with “generate” and even say: this is my problem, code it for me. But it’s much more fun to First struggle and then ask for help, because otherwise you just don’t learn anything.


Are you still with me? Then let’s dig the next level of questions, which are maybe less technical, and more philosophical.

Follow-up questions:

  • Do you need to set an intention for the I-Ging to get guidance?

  • What about state preparation to reflect the “cosmic context”?

  • Who do you encode your intention?

  • Does this make sense? At all?

So, let’s start with these.

Do you need to set an intention for the I-Ging to get guidance?

Well, yes, or no. You decide, The I-Ging was previously a tool to understand cosmic relations, doing divination, so you can use it specifically to answer a question and then check for guidance in the changing lines and their recommendations.

If I use them simply to generate a random number which gives the key to the question out of the question pool, then - well, you can think in cosmic terms of course it makes sense to think of the quest who should get the question, and the let the thing fly, and hope that the cosmos is wise enough to have an influence on the Hardware doing the quantum execution somewhere in a data center. I’ll give some examples later below.

Which leads over logically to the next question.

What about state preparation to reflect the “cosmic context”?

Which is a good one, because as we have seen in the beginning a quantum computer sets all states to zero, then the algorithm starts fresh, i.e. rotating the zero state accordingly, and then doing the measurement, which leads to the result, depending on - well Random. Where this random comes from, is one of the fundamental questions. How the quantum things know how to adhere to the distribution is the magic, also known as Born rule. Nobody knows why this is as it is. We definitely cannot touch it here, but it’s one thing that bothers me.

Doing different kind of state preparation to reflect any background info - however you might want to encode this remains open - either as amplitude or phase, is not needed, and also in the natural divination, when you use the sticks, you always revert back to the pile, and start from scratch, there likely is no influence encoded IN the stalks - which would be the equivalent of a state preparation. While also this is speculation, maybe the stalks you pick, - or in case you chose coins - the people who had the coin before you somewhat influence the result of the toss. who knows. The Cosmos does. We don’t.

How do you encode your intention?

Well, I think - you do NOT encode intention. There are these online I-Ging where you type your intention before - maybe they use it to generate a hash which directs the seed for your random generator - because likely the generate they use is not quantum.

If we really use a real quantum computer hardware - there is no random seed.

Which is a bit of a mehhh…. result, agreed, because there is nothing you can do technically to influence anything. You can of course think, and entangle minds and intentions with the outcome - maybe on higher dimensions, for the technical nerds, there is nothing to see in our 4 dimensions (space and time).

Does this make sense then? At all?

That is the unanswered question. That’s why we need to do the experiment. Only experiments show results. Then we can hope to understand them - or not, but only nature shows nature.

I like the fact of having a real quantum computer, and run some mini jobs there, which result in a sequence of (defined per target probgability distribution) random readings of 0 and 1 - and then translate it to a number - the I-Ging, some additions, and then - because I like to do that as experiment - load the respective question out of the pool and look what happens.

Here how it looks, the code including mapping etc. is at the end for the real fans.

Even more follow-up questions:

  • Do I have a good example how the QRNG picked an interesting question?

  • Could I have achieved that without QRNG?

  • What would I expect from the I-Ching approach?

  • Do I need a random question at all?

  • What alternatives exist?

Let’s start with the last one first, alternatives to QRNG, and some insights where in the podcast the QRNG produced great unexpected twist.

Alternatives to QRNG computation on a quantum computer

Yes, there are other methods that produce real cosmic noise, i.e. not digitally computed “random” but real random.

There are some devices that produce random numbers based on measuring quantum effects directly, e.g. the time between radioactive decay, or the photons emitted from a LED in a given time slot. These are commercial available devices, you can also measure cosmic noise etc. but in my case, having it at hand from my Mac is quite nice, and integrated.

Do I have a good example how the QRNG picked an interesting question and … could I have achieved that without QRNG?

Answer to the first part: Yes. Several. And they did produce surprising input and steered the conversation to beautiful directions. Quasi in all episodes in 2025 where I used it.

And yes, I did run them WITH the INTENT give me a great question for THIS Guest. Something I would not have thought of.

  • Remember e.g. Paul Werbos - the impact of music, I think this was one of the most moving moments so far on the podcast - if you have time, watch the video (linked in the article here).

  • Also for Dean Radin, I shared one before that was picked while we had a pre-discussion, but during the interview I let it run again, and it was fitting to the discussion we had just before.

also the other guests gave interesting answers to the questions, and it felt somewhat related to them, but these two are really remarkable, maybe due to the the fact that themselves are very open to the potential correlation (whatever the mechanism).

Now, could I have achieved that without a QRNG? I honestly don’t know, in these cases it felt that it really worked.

Of courese I could have played Darts or throw dice or whatever to pick a random question. Yes. Sure.

Funny enough, it picked for the very first episode, for which I do not have a dedicated Substack article, just the link to the podcast, with Sadegh Ebrahimi “What did you learn from a podcast?” - and he mentioned the Telepathy Tapes as his favorite podcast - which is a great podcast, and somewhat entangled to my podcast, even if they have much more listeners, we share some guests - which I likely knew before them got to know them. So e.g. we both share Neil Theise as recent guest - while for him I had not a QRNG question.

The question is maybe not so much the Q in QRNG but the fact of a random question itself.

For my deepest fans, here the bonus, of course: the python code with link the I-Ging symbols and their mappings, build a link to the numbers of the “question pool”, and some learnings answering the remaining one

  • Do I need a random question at all?

User's avatar

Continue reading this post for free, courtesy of Thomas Ehmer.

Or purchase a paid subscription.
© 2026 Thomas Ehmer · Privacy ∙ Terms ∙ Collection notice
Start your SubstackGet the app
Substack is the home for great culture