Sub topic 8
Encoding machines and the universal Turing machine
This chapter assumes you can trace a deterministic Turing machine (TM) through its configurations. It also assumes you know the difference between a decider and a recognizer, and that you know what countable and uncountable sets are. The chapter shows how a machine becomes a string, and how one fixed machine can run any other machine given that string.
Why machines must be strings
A TM's input is a string. To ask questions such as "does machine M accept input w?", the question itself has to be a string. So we fix a way to write a machine down. The written form of M is its encoding, written ⟨M⟩. A pair is written ⟨M, w⟩.
Nearly every undecidability result in later chapters depends on this step. A TM can take another TM, or itself, as input.
Writing a machine as a string
A TM is a finite object. Its states, tape alphabet and transition table are all finite. Any finite object can be written as a string over a small alphabet. The textbook method uses only 0 and 1:
- Number the states q1, q2, … and the symbols a1, a2, …. Number the directions L = 1 and R = 2.
- Write each number n as 0^n.
- Write one transition δ(qi, aj) = (qk, al, D) as 0^i 1 0^j 1 0^k 1 0^l 1 0^D.
- Join the transitions with 11, with the start state, accept state and symbol conventions fixed in advance.
The exact scheme does not matter. A valid scheme has three properties:
- Different machines get different strings.
- A fixed procedure can decode the string back into the machine.
- A procedure can check whether a string is a valid encoding.
Checking validity is easy, so the language of valid encodings is decidable. A random string is usually not a valid encoding. The usual convention is that any invalid string stands for a fixed machine that rejects everything. With that convention, every string in {0,1}* encodes some TM.
Consequences of encoding
- The set of all TMs is countable. List all binary strings in order of length, then alphabetically within each length. Each string maps to a machine, so the machines can be numbered M1, M2, M3, ….
- The set of all languages over {0,1} is uncountable, because it has the size of the power set of {0,1}*.
- Therefore some languages have no TM at all. The diagonalization chapter turns this counting argument into a concrete example.
The universal Turing machine
A universal Turing machine U takes input ⟨M, w⟩ and behaves as M would on w:
- If M accepts w, then U accepts.
- If M rejects w, then U rejects.
- If M loops on w, then U loops.
So L(U) = A_TM = { ⟨M, w⟩ : M accepts w }.
U is a single fixed machine, yet it runs every other machine. This is the theoretical model of a stored-program computer. The "program" ⟨M⟩ is data on the tape, and U is the processor that interprets it.
How U works (three-tape sketch)
Using a multi-tape machine is allowed because it is equivalent in power to a one-tape machine.
- Tape 1 holds the description ⟨M⟩, which is never changed.
- Tape 2 holds the simulated tape of M, initialized to w.
- Tape 3 holds M's current state.
Each simulated step does the following:
- Read the state from tape 3 and the symbol under the head on tape 2.
- Scan tape 1 for the matching transition.
- Write the new symbol on tape 2, move the simulated head, and update tape 3.
- If the new state is the accept state, accept. If no transition matches, reject.
The loop in the diagram has no step limit. If M loops forever on w, then U loops forever too. That is why U is only a recognizer, and it is the core of the next chapters.
A working miniature in Python
The code below encodes a machine as a string, decodes it, and runs a universal simulator that takes only the string and the input. It reuses the a^n b^n machine from the earlier chapters. Invalid encodings reject, following the convention above. The step limit stands in for "keep running"; real U has no such limit.
def encode(delta):
parts = []
for (q, a), (p, b, d) in sorted(delta.items()):
parts.append(f"{q},{a},{p},{b},{d}")
return ";".join(parts)
def decode(s):
delta = {}
if s == "":
return delta
for part in s.split(";"):
q, a, p, b, d = part.split(",") # ValueError if malformed
if d not in ("L", "R"):
raise ValueError("bad direction")
delta[(q, a)] = (p, b, d)
return delta
def universal(code, w, max_steps=10000):
"""Return True/False, or None if the step limit is reached."""
try:
delta = decode(code)
except ValueError:
return False # invalid code = machine that rejects all
tape = dict(enumerate(w))
head, state = 0, "q0"
for _ in range(max_steps):
if state == "qa":
return True
key = (state, tape.get(head, "_"))
if key not in delta:
return False
state, sym, move = delta[key]
tape[head] = sym
head += 1 if move == "R" else -1
return None
delta = {
('q0', 'a'): ('q1', 'X', 'R'), ('q0', 'Y'): ('q3', 'Y', 'R'),
('q0', '_'): ('qa', '_', 'R'), ('q1', 'a'): ('q1', 'a', 'R'),
('q1', 'Y'): ('q1', 'Y', 'R'), ('q1', 'b'): ('q2', 'Y', 'L'),
('q2', 'a'): ('q2', 'a', 'L'), ('q2', 'Y'): ('q2', 'Y', 'L'),
('q2', 'X'): ('q0', 'X', 'R'), ('q3', 'Y'): ('q3', 'Y', 'R'),
('q3', '_'): ('qa', '_', 'R'),
}
code = encode(delta)
print(code[:40], "...")
for w in ["", "ab", "aabb", "aab", "abb"]:
print(repr(w), universal(code, w))
print("garbage code:", universal("not a machine", "ab"))
# '' True, 'ab' True, 'aabb' True, 'aab' False, 'abb' False
# garbage code: FalseThe function universal never mentions a^n b^n. Its behavior comes entirely from the data in code.
What the universal machine does and does not give us
| Language | Recursive (decidable)? | Recursively enumerable? |
|---|---|---|
| Valid encodings of TMs | Yes | Yes |
| A_TM = { ⟨M, w⟩ : M accepts w } | No | Yes, U recognizes it |
| Complement of A_TM | No | No |
ATM is recursively enumerable because U recognizes it. The next chapters show that ATM is not recursive. Together with the closure result that a language and its complement both being RE implies recursive, this also shows that the complement of A_TM is not RE.
Common errors and GATE shortcuts
- "U decides A_TM." It does not. U recognizes A_TM and may loop on inputs outside it.
- "There are uncountably many TMs." There are only countably many, because each is a finite string. The uncountable set is the set of languages.
- Confusing ⟨M⟩ with L(M). ⟨M⟩ is a string describing the machine. L(M) is the set of strings M accepts. Different machines can have the same language but never the same encoding.
- Simulation cost. Simulating t steps of M takes about t times the size of ⟨M⟩ steps on U. A one-tape U is slower again, but this never changes what is computable.
- Statement pattern. "A universal TM exists" is true. "A universal TM that always halts exists" is false, since it would decide A_TM.
Exercise
The set of all Turing machines is countable, yet some languages are not recognized by any Turing machine. Explain why both statements are true.
Show answer
Each Turing machine has a finite description, so its encoding is a finite binary string. The set of finite binary strings is countable, so the machines can be listed M1, M2, M3, …. Each machine recognizes exactly one language, so only countably many languages are recognized. The set of all languages over {0,1} is the power set of {0,1}*, which is uncountable. Uncountably many languages cannot be matched to countably many machines, so some languages have no recognizing machine.
Exercise
Let U be the universal machine. Which of these is true: (a) U decides ATM, (b) U recognizes ATM, (c) U halts on every input ⟨M, w⟩? Justify your choice.
Show answer
Only (b) is true. U accepts exactly the pairs where M accepts w, so L(U) = ATM. If M loops on w, U simulates it forever and also loops, so (c) is false. Because U can loop on some inputs, it is not a decider, so (a) is false. ATM is in fact undecidable.