কম্পিউটার বিজ্ঞান · বই 3 · স্নাতক প্রথম বর্ষ

University Computer Science — Year 1

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

University Computer Science — Year 1 · স্নাতক প্রথম বর্ষ

27Boolean Algebra and Combinational Circuits

The adder inside a processor adds two 64-bit numbers in a fraction of a nanosecond. It is built from gates, each of which knows only one or two bits and computes a function as simple as “both” or “either”. This chapter is about how such gates are combined: how any function of bits can be written with them, how to write it with few, why one kind of gate is enough, and how the arrangement of the gates, not their number, decides the speed of an adder. The circuits are built and run in a small simulator, in which a circuit is what it is in the hardware: a directed acyclic graph of gates.

You already know

Gates and the half adder were built in the first book; the second built an adder and a multiplexer. Formulas, their truth tables and the normal forms DNF and CNF are in Definition 10.7; DAGs and their longest paths in Chapters 24 and 25.

27.1 Boolean functions and canonical forms

Definition 27.1 (Boolean function)

A Boolean function of nn variables is a function f ⁣:{0,1}n→{0,1}f\colon \{0, 1\}^n \to \{0, 1\}. It is given by its truth table, 2n2^n rows; so there are 22n2^{2^n} Boolean functions of nn variables.

We write x′x' for the negation of xx, xyxy for the conjunction and x+yx + y for the disjunction. These operations obey the laws of Boolean algebra: commutativity and associativity of ++ and of the product; each distributes over the other, x(y+z)=xy+xzx(y + z) = xy + xz and x+yz=(x+y)(x+z)x + yz = (x + y)(x + z); x+0=xx + 0 = x, x⋅1=xx \cdot 1 = x, x+x′=1x + x' = 1, xx′=0x x' = 0; and De Morgan’s laws (x+y)′=x′y′(x + y)' = x' y', (xy)′=x′+y′(xy)' = x' + y'. Each is checked on the four (or eight) rows of a truth table. Boole set them out in 1854 as laws of thought; in 1938 Shannon showed that they describe circuits of relays.

George Boole, whose book of 1854 set out these laws as the laws of thought. Portrait by an unknown artist, public domain.
George Boole, whose book of 1854 set out these laws as the laws of thought. Portrait by an unknown artist, public domain.

Definition 27.2 (Minterm, maxterm, canonical forms)

A minterm of nn variables is a product in which every variable appears once, plain or negated: it is 1 on exactly one row. A maxterm is a sum in which every variable appears once: it is 0 on exactly one row. The canonical sum of products of ff is the sum of the minterms of the rows where ff is 1; its canonical product of sums is the product of the maxterms of the rows where ff is 0.

Both equal ff: the sum is 1 exactly on the rows of its minterms, and the product 0 exactly on the rows of its maxterms. They are the DNF and CNF of Chapter 10 read off a truth table, and they prove that negation, conjunction and disjunction can express every Boolean function.

def sum_of_products(f, names):
    terms = []
    for row in product((0, 1), repeat=len(names)):
        if f(*row):  # a minterm: true on this row only
            terms.append("".join(literal(n, v, 1) for n, v in zip(names, row)))
    return " + ".join(terms)


def product_of_sums(f, names):
    factors = []
    for row in product((0, 1), repeat=len(names)):
        if not f(*row):  # a maxterm: false on this row only
            literals = [literal(n, v, 0) for n, v in zip(names, row)]
            factors.append("(" + " + ".join(literals) + ")")
    return "".join(factors)
Listing 27.1. The canonical forms from the truth table code/bachelor-1/27-combinational-circuits/listings/canonical.py
$ python canonical.py
a b c | maj
0 0 0 | 0
0 0 1 | 0
0 1 0 | 0
0 1 1 | 1
1 0 0 | 0
1 0 1 | 1
1 1 0 | 1
1 1 1 | 1
sum of products: a'bc + ab'c + abc' + abc
product of sums: (a + b + c)(a + b + c')(a + b' + c)(a' + b + c)
functions of n variables: [4, 16, 256, 65536, 4294967296]
Output 27.1. The majority of three bits, its two canonical forms, and the number of functions of 1 to 5 variables.

Definition 27.3 (Combinational circuit)

A combinational circuit is a directed acyclic graph whose sources are the inputs, whose other vertices are logic gates, each fed by the vertices it has arcs from, and some of whose vertices are marked as outputs. Its outputs depend only on its current inputs.

The simulator stores the gates in the order they were added; a gate may only use wires that exist already, so that order is topological, and evaluation is one pass, as for the DAG paths of Chapter 25.

    def gate(self, op, *ins):
        """Add a gate whose inputs are existing wires; return its output wire."""
        known = set(self.inputs) | {w for w, _, _ in self.gates}
        assert all(i in known for i in ins), "a gate may only use existing wires"
        wire = f"w{len(self.gates)}"
        self.gates.append((wire, op, ins))
        return wire

    def evaluate(self, values):
        """values: input wire -> 0 or 1. Returns the value of every output."""
        v = dict(values)
        for wire, op, ins in self.gates:  # every input is computed before
            v[wire] = OPS[op]([v[i] for i in ins])
        return {name: v[w] for name, w in self.outputs.items()}

    def delay(self):
        """The longest path from an input to an output, counted in gates."""
        depth = {i: 0 for i in self.inputs}
        for wire, _, ins in self.gates:
            depth[wire] = 1 + max((depth[i] for i in ins), default=0)
        return max(depth[w] for w in self.outputs.values())
Listing 27.2. The simulator: adding a gate, evaluating, and the delay code/bachelor-1/27-combinational-circuits/listings/circuit.py

27.2 Simplification

The majority function needs four products of three literals in its canonical form, but ab+ac+bcab + ac + bc will do. Algebra finds it: abcabc can be repeated, a′bc+abc=bca'bc + abc = bc, and so on. A picture finds it faster.

Definition 27.4 (Karnaugh map)

A Karnaugh map of a function of four variables is its truth table arranged as a 4×44 \times 4 grid, rows labelled by abab and columns by cdcd in the order 00,01,11,1000, 01, 11, 10, so that two neighbouring cells, the first and last of a row or column included, differ in exactly one variable.

Two neighbouring 1 cells merge into a product without the variable in which they differ; four cells in a 2×22 \times 2 square or a row of four lose two variables; eight cells lose three. Groups must be rectangles of 11, 22, 44 or 88 cells, possibly wrapping around the edges.

Definition 27.5 (Implicant, prime implicant, essential prime implicant, don’t-care)

An implicant of ff is a product of literals that is 1 only where ff is 1. It is prime if removing any literal makes it cover a 0 of ff, and essential if it is the only prime implicant covering some 1 of ff. A don’t-care condition is a row whose output does not matter, because it never occurs; it may be covered or not, as suits the simplification.

A minimal sum of products is made of prime implicants (a non-prime one can lose a literal) and contains every essential one. The program finds the prime implicants by merging terms that differ in one variable, round after round, the method of Quine and McCluskey; with four variables, a Karnaugh map shows the same groups at a glance.

def merge(s, t):
    """Two terms such as '0-11' and '1-11' that differ in one position give '--11'."""
    diff = [i for i in range(len(s)) if s[i] != t[i]]
    if len(diff) == 1 and "-" not in (s[diff[0]], t[diff[0]]):
        return s[:diff[0]] + "-" + s[diff[0] + 1:]
    return None


def prime_implicants(ones, dont_care=(), n=4):
    terms = {format(m, f"0{n}b") for m in set(ones) | set(dont_care)}
    primes = set()
    while terms:
        merged, used = set(), set()
        for s in terms:
            for t in terms:
                m = merge(s, t)
                if m:
                    merged.add(m)
                    used |= {s, t}
        primes |= terms - used  # a term that merges with nothing is prime
        terms = merged
    return sorted(primes)
Listing 27.3. Prime implicants by repeated merging; - marks a variable that has gone code/bachelor-1/27-combinational-circuits/listings/karnaugh.py
$ python karnaugh.py
ab\cd 00  01  11  10
  00   1   1   .   1
  01   .   1   1   1
  11   .   .   .   1
  10   1   1   .   1
prime implicants: cd', b'd', b'c', a'c'd, a'bd, a'bc
essential: cd', b'c'
Output 27.2. The map of a function of four variables, its six prime implicants and the two essential ones.
The map of  covered by three prime implicants: f = cd' + b'c' + a'bd. The two essential ones leave the cells 5 and 7 bare; a'bd covers both, where a'c'd or a'bc would cover only one.
The map of Output 27.2 covered by three prime implicants: f=cd′+b′c′+a′bdf = cd' + b'c' + a'bd. The two essential ones leave the cells 5 and 7 bare; a′bda'bd covers both, where a′c′da'c'd or a′bca'bc would cover only one.

A seven-segment display shows a digit with seven lit bars, named aa to gg. Its decoder takes the digit in four bits; the codes 10 to 15 never occur, and the don’t-cares let the groups grow.

$ python seven_segment.py
a = c + b'd' + bd + a           correct on 0-9: True
b = c'd' + cd + b'              correct on 0-9: True
c = d + c' + b                  correct on 0-9: True
d = cd' + b'd' + b'c + bc'd + a correct on 0-9: True
e = cd' + b'd'                  correct on 0-9: True
f = c'd' + bd' + bc' + a        correct on 0-9: True
g = b'c + bc' + a + cd'         correct on 0-9: True
42 literals in all, against 196 in the canonical sums
Output 27.3. The seven segments, each simplified with the codes 10 to 15 as don’t-cares, and checked on the ten digits. The variables are abcdabcd, aa the high bit.

27.3 NAND alone is enough

Definition 27.6 (Functionally complete set)

A set of Boolean operations is functionally complete if every Boolean function of any number of variables can be computed by a circuit of gates from the set.

The canonical forms show that {NOT,AND,OR}\{\text{NOT}, \text{AND}, \text{OR}\} is complete; by De Morgan, so are {NOT,AND}\{\text{NOT}, \text{AND}\} and {NOT,OR}\{\text{NOT}, \text{OR}\}.

Proposition 27.7 (NAND is complete)

{NAND}\{\text{NAND}\} is functionally complete.

Proof. x′=NAND(x,x)x' = \text{NAND}(x, x) and xy=NAND(x,y)′xy = \text{NAND}(x, y)', so NOT and AND are expressed with NAND, and {NOT,AND}\{\text{NOT}, \text{AND}\} is complete. ∎

def nand_not(c, x):
    return c.gate("NAND", x, x)


def nand_and(c, x, y):
    return nand_not(c, c.gate("NAND", x, y))


def nand_or(c, x, y):
    return c.gate("NAND", nand_not(c, x), nand_not(c, y))  # De Morgan


def nand_xor(c, x, y):
    n = c.gate("NAND", x, y)
    return c.gate("NAND", c.gate("NAND", x, n), c.gate("NAND", y, n))
Listing 27.4. NOT, AND, OR and XOR from NAND gates code/bachelor-1/27-combinational-circuits/listings/nand_only.py
$ python nand_only.py
NOT: NAND gates 1, delay 1, correct: True
AND: NAND gates 2, delay 2, correct: True
OR : NAND gates 3, delay 2, correct: True
XOR: NAND gates 4, delay 3, correct: True
Output 27.4. Each construction checked on its four inputs.
NOT, AND and OR from NAND gates, as in : one, two and three gates.
NOT, AND and OR from NAND gates, as in Listing 27.4: one, two and three gates.

Not every set is complete. A function is monotone if raising an input from 0 to 1 never lowers the output; AND and OR are monotone, and so is any circuit of AND and OR gates, by induction along the DAG. NOT is not monotone, so {AND,OR}\{\text{AND}, \text{OR}\} is not complete (Exercise 27.10). Sheffer showed in 1913 that one operation, the “stroke” now called NAND, suffices for all of Boolean algebra. In hardware a NAND gate is the cheapest: a few transistors used as switches, the physics of which belongs to the physics books.

History — Gates on a chip

In the 1960s, gates stopped being wired one by one from separate parts and began to be made together on one chip of silicon, an integrated circuit. In 1966 Texas Instruments announced its 7400 series of such chips in cheap plastic packages. The 7400 itself holds four independent two-input NAND gates in a package of 14 pins: three for each gate, and two for the power supply. Circuits like those of this chapter were then built by wiring such chips together on a board.

A 7400 chip in its plastic package with two rows of seven pins. Inside are the four NAND gates; the notch marks the end where pin 1 is. Photograph: Mister rf, CC BY-SA 4.0.
A 7400 chip in its plastic package with two rows of seven pins. Inside are the four NAND gates; the notch marks the end where pin 1 is. Photograph: Mister rf, CC BY-SA 4.0.

27.4 Arithmetic and routing

Definition 27.8 (Full adder, ripple-carry adder)

A full adder adds three bits aa, bb and a carry in cc: its sum is a⊕b⊕ca \oplus b \oplus c and its carry out is ab+c(a⊕b)ab + c(a \oplus b), where ⊕\oplus is XOR. A ripple-carry adder of nn bits chains nn full adders, the carry out of each feeding the carry in of the next.

Subtraction comes free: in two’s complement, a−b=a+b′+1a - b = a + b' + 1, where b′b' inverts every bit; XOR gates with a control bit invert bb on demand, and the same bit is the first carry in.

The carry is the trouble: bit ii cannot finish before bit i−1i - 1, and the last carry waits for the whole chain. The way out is to compute every carry directly from the inputs. Write gi=aibig_i = a_i b_i (bit ii generates a carry) and pi=ai⊕bip_i = a_i \oplus b_i (it propagates the carry it receives). Then ci+1=gi+picic_{i+1} = g_i + p_i c_i, and unrolling,

ci+1=gi+pigi−1+pipi−1gi−2+⋯+pipi−1⋯p0c0.c_{i+1} = g_i + p_i g_{i-1} + p_i p_{i-1} g_{i-2} + \dots + p_i p_{i-1} \cdots p_0 c_0.

Definition 27.9 (Generate and propagate, carry-lookahead adder)

The signals gig_i and pip_i are the generate and propagate signals. A carry-lookahead adder computes the carries of a block of bits by the unrolled formula, with one level of AND gates and one OR gate per carry.

def lookahead_block(c, a, b, cin):
    """Four bits: c_{i+1} = g_i + p_i g_{i-1} + ... + p_i ... p_0 c_0, two levels."""
    g = [c.gate("AND", x, y) for x, y in zip(a, b)]
    p = [c.gate("XOR", x, y) for x, y in zip(a, b)]
    carries = [cin]
    for i in range(4):
        terms = [g[i]]
        for j in range(i - 1, -2, -1):  # g_j (or c_0) carried through p_{j+1} ... p_i
            src = g[j] if j >= 0 else cin
            terms.append(c.gate("AND", src, *p[j + 1:i + 1]))
        carries.append(c.gate("OR", *terms))
    sums = [c.gate("XOR", p[i], carries[i]) for i in range(4)]
    return sums, carries[4]
Listing 27.5. A 4-bit lookahead block code/bachelor-1/27-combinational-circuits/listings/adders.py
Left, a 4-bit ripple-carry adder: each full adder waits for the carry of the one before. Right, a lookahead block: generate and propagate in one gate delay, all four carries in two more, the sums in one more.
Left, a 4-bit ripple-carry adder: each full adder waits for the carry of the one before. Right, a lookahead block: generate and propagate in one gate delay, all four carries in two more, the sums in one more.

Definition 27.10 (Multiplexer, decoder)

A 2k2^k-to-1 multiplexer has 2k2^k data inputs and kk select inputs, and outputs the data input whose number the select inputs spell. A kk-to-2k2^k decoder has kk inputs and 2k2^k outputs, of which exactly the one numbered by the inputs is 1.

A 2-to-1 multiplexer is s′x0+sx1s' x_0 + s x_1; a decoder is one AND gate per minterm. Multiplexers route information: they choose which result goes on.

Definition 27.11 (Arithmetic and logic unit)

An arithmetic and logic unit (ALU) computes, from two operands and an operation code, one of several results, chosen by multiplexers, and flags that describe it: ZZ (zero), NN (negative, the top bit), CC (carry out) and VV (overflow in two’s complement).

def alu():
    c = Circuit(*[f"a{i}" for i in range(4)], *[f"b{i}" for i in range(4)],
                "op1", "op0")
    sub = c.gate("AND", "op1", "op0")
    carry, result = sub, []  # a - b = a + (not b) + 1
    for i in range(4):
        b = c.gate("XOR", f"b{i}", sub)
        s, carry = full_adder(c, f"a{i}", b, carry)
        both, either = c.gate("AND", f"a{i}", f"b{i}"), c.gate("OR", f"a{i}", f"b{i}")
        logic = mux(c, "op0", both, either)
        result.append(mux(c, "op1", logic, s))
        if i == 3:
            same_signs = c.gate("NOT", c.gate("XOR", "a3", b))
            overflow = c.gate("AND", "op1", same_signs, c.gate("XOR", s, "a3"))
    for i, r in enumerate(result):
        c.outputs[f"r{i}"] = r
    c.outputs |= {"Z": c.gate("NOR", *result), "N": result[3],
                  "C": c.gate("AND", "op1", carry), "V": overflow}
    return c
Listing 27.6. A 4-bit ALU: AND, OR, addition and subtraction code/bachelor-1/27-combinational-circuits/listings/alu.py
$ python alu.py
71 gates, delay 13; all 1024 cases correct: True
ADD  2  3 ->  5 = 0101  Z=0 N=0 C=0 V=0
ADD  7  1 ->  8 = 1000  Z=0 N=1 C=0 V=1
ADD  9  9 ->  2 = 0010  Z=0 N=0 C=1 V=1
SUB  5  7 -> 14 = 1110  Z=0 N=1 C=0 V=0
SUB  6  6 ->  0 = 0000  Z=1 N=0 C=1 V=0
AND 12 10 ->  8 = 1000  Z=0 N=1 C=0 V=0
OR  12 10 -> 14 = 1110  Z=0 N=1 C=0 V=0
Output 27.5. Checked against integer arithmetic on all 1024 cases; 7+17 + 1 overflows in signed 4-bit arithmetic, and 9+99 + 9 carries out.

Overflow happens when the two operands of the addition have the same sign and the result the other one; the circuit tests exactly that, on the top bits.

27.5 Propagation delay

Definition 27.12 (Propagation delay, longest delay path)

Each gate takes a small time, its propagation delay, to update its output. The delay of a circuit is the largest total delay along a path from an input to an output, a longest delay path. With every gate counted as one delay, as in the simulator, it is the longest path of the DAG, counted in gates.

$ python adders.py
4 bits, ripple-carry:  20 gates, delay  9, all 512 sums correct: True
4 bits, lookahead   :  26 gates, delay  4, all 512 sums correct: True
8 bits, ripple-carry:  40 gates, delay 17, all 131072 sums correct: True
8 bits, lookahead   :  52 gates, delay  6, all 131072 sums correct: True
16 bits: delay  33 rippling, 10 with lookahead blocks
32 bits: delay  65 rippling, 18 with lookahead blocks
64 bits: delay 129 rippling, 34 with lookahead blocks
Output 27.6. Sizes and delays of the two adders, both checked on every input for 4 and 8 bits.

The ripple-carry adder has delay 2n+12n + 1 (Exercise 27.11): linear in the number of bits. A lookahead block has delay 4 whatever the carry in, at the price of more gates, and of gates with many inputs, which real hardware limits. Rippling between blocks of four still costs two delays per block. Lookahead applied again to the blocks, in a tree of lookahead units, brings the delay to O(log⁡n)O(\log n); processors add 64 bits that way, within a clock cycle.

27.6 Exercises

Exercise 27.1 ★

Give the truth table of the circuit f=OR(AND(a,NOT(b)),AND(b,c))f = \text{OR}(\text{AND}(a, \text{NOT}(b)), \text{AND}(b, c)), and its delay.

Solution

Solution of Exercise 27.1.

f=ab′+bcf = ab' + bc is 1 on the rows abc=011,100,101,111abc = 011, 100, 101, 111 and 0 on the others. The longest path is NOT, AND, OR: delay 3.

Exercise 27.2 ★

The function f(a,b,c)f(a, b, c) is 1 exactly when an odd number of its inputs are 1. Write its canonical sum of products, and explain why no Karnaugh grouping shortens it.

Solution

Solution of Exercise 27.2.

f=a′b′c+a′bc′+ab′c′+abcf = a'b'c + a'bc' + ab'c' + abc. Two neighbouring cells of a Karnaugh map differ in one variable, so their numbers of 1 inputs differ by one and their values of ff differ: no two 1 cells are neighbours, and no group is larger than one cell.

Exercise 27.3 ★

Using the map of Output 27.2, find another minimal sum of products, if there is one, and say why every minimal sum has at least three products.

Solution

Solution of Exercise 27.3.

The essential cd′cd' and b′c′b'c' cover every 1 but the cells 5 and 7. Only a′bda'bd among the prime implicants covers both; a′c′da'c'd covers 5 and a′bca'bc covers 7, which needs two products. So f=cd′+b′c′+a′bdf = cd' + b'c' + a'bd is the only minimal sum; it needs three products, since the two essential ones must be there and do not cover everything.

Exercise 27.4 ★

What does the ALU of Listing 27.6 output for the operation code 11 with a=3a = 3 and b=9b = 9? Give the four flags, and interpret them as unsigned and as signed numbers.

Solution

Solution of Exercise 27.4.

The code 11 is subtraction: 3−9+16=10=10103 - 9 + 16 = 10 = 1010, with Z=0Z = 0, N=1N = 1, C=0C = 0, V=1V = 1. Unsigned, C=0C = 0 means a borrow: 3<93 < 9 and the result has wrapped round. Signed, 99 is −7-7 and 3−(−7)=103 - (-7) = 10 does not fit in 4 bits: V=1V = 1, and the result read as −6-6 is wrong.

Exercise 27.5 ★★

A student labels the columns of a Karnaugh map 00,01,10,1100, 01, 10, 11 and the rows likewise, then groups the two middle 1s of the row ab=00ab = 00 of a function that is 1 on the minterms 1 and 2 only, writing a′b′a'b' times “whatever cdcd is”. What went wrong, and what is the correct sum?

Solution

Solution of Exercise 27.5.

In the order 00,01,10,1100, 01, 10, 11, the middle columns 0101 and 1010 sit side by side but differ in two variables, cc and dd: they are not neighbours, and the two cells do not form a product. The minterms 1 and 2 stay apart: f=a′b′c′d+a′b′cd′f = a'b'c'd + a'b'cd'. The Gray order 00,01,11,1000, 01, 11, 10 makes the drawing tell the truth.

Exercise 27.6 ★★

This full adder assembles its carry differently. On which row is it wrong, and why on that row only?

c = Circuit("a", "b", "cin")
c.outputs["s"] = c.gate("XOR", c.gate("XOR", "a", "b"), "cin")
c.outputs["cout"] = c.gate("XOR", c.gate("AND", "a", "b"),
                           c.gate("AND", "cin", c.gate("OR", "a", "b")))
Listing 27.7. Another carry code/bachelor-1/27-combinational-circuits/listings/exo_carry_xor.py
wrong on a=1 b=1 cin=1: carry 0
Output 27.7. Every row checked. Some lines are left out.
Solution

Solution of Exercise 27.6.

It computes ab⊕c(a+b)ab \oplus c(a + b). The two products are both 1 only when a=b=1a = b = 1 and c=1c = 1, and then XOR gives 0 where the carry is 1. On every other row at most one of them is 1, and XOR agrees with OR. The textbook carry ab+c(a⊕b)ab + c(a \oplus b) has the same property, so there either gate works; with a+ba + b inside, only OR does.

Exercise 27.7 ★★

Build a 2-to-1 and a 4-to-1 multiplexer in the simulator, and test them on every input.

Solution

Solution of Exercise 27.7.

def mux2(c, s, x0, x1):
    return c.gate("OR", c.gate("AND", c.gate("NOT", s), x0), c.gate("AND", s, x1))


def mux4():
    """Output x[2 s1 + s0]: two levels of 2-to-1 multiplexers."""
    c = Circuit("s1", "s0", "x0", "x1", "x2", "x3")
    low, high = mux2(c, "s0", "x0", "x1"), mux2(c, "s0", "x2", "x3")
    c.outputs["out"] = mux2(c, "s1", low, high)
    return c
Multiplexers code/bachelor-1/27-combinational-circuits/exercises/mux.py

The 4-to-1 multiplexer is two 2-to-1 multiplexers on s0s_0 followed by one on s1s_1: 12 gates, delay 5. The test tries the 64 inputs.

Exercise 27.8 ★★

Build a circuit that outputs a<ba < b for two 4-bit unsigned numbers, test it on every input, and give its delay.

Solution

Solution of Exercise 27.8.

def less_than():
    c = Circuit(*[f"a{i}" for i in range(4)], *[f"b{i}" for i in range(4)])
    eq = [c.gate("NOT", c.gate("XOR", f"a{i}", f"b{i}")) for i in range(4)]
    lt = [c.gate("AND", c.gate("NOT", f"a{i}"), f"b{i}") for i in range(4)]
    terms = [c.gate("AND", lt[i], *eq[i + 1:]) if i < 3 else lt[3] for i in range(4)]
    c.outputs["lt"] = c.gate("OR", *terms)
    return c
a<ba < b on four bits code/bachelor-1/27-combinational-circuits/exercises/compare.py

a<ba < b when, at some bit ii, ai=0a_i = 0 and bi=1b_i = 1 while all higher bits are equal. One OR of four products: 20 gates, delay 4 (XOR, NOT, AND, OR). The test tries the 256 pairs.

Exercise 27.9 ★★

Count the monotone Boolean functions of nn variables for n≤3n \leq 3, by program and by argument for n≤2n \leq 2.

Solution

Solution of Exercise 27.9.

def monotone_count(n):
    rows = list(product((0, 1), repeat=n))
    count = 0
    for table in product((0, 1), repeat=len(rows)):
        f = dict(zip(rows, table))
        if all(f[x] <= f[y] for x in rows for y in rows
               if all(a <= b for a, b in zip(x, y))):
            count += 1
    return count
Monotone functions, by brute force code/bachelor-1/27-combinational-circuits/exercises/monotone.py

The program finds 2, 3, 6 and 20 for n=0,1,2,3n = 0, 1, 2, 3, against 2,4,16,2562, 4, 16, 256 functions in all. For n=1n = 1: the constants and xx (x′x' is not monotone). For n=2n = 2: the constants, xx, yy, xyxy and x+yx + y; any other function is 1 on some row and 0 on a row above it.

Exercise 27.10 ★★★

Prove that {NOR}\{\text{NOR}\} is functionally complete, and that {AND,OR}\{\text{AND}, \text{OR}\} is not.

Solution

Solution of Exercise 27.10.

x′=NOR(x,x)x' = \text{NOR}(x, x) and x+y=NOR(x,y)′x + y = \text{NOR}(x, y)': NOR expresses NOT and OR, a complete set by De Morgan. For the second part, every circuit of AND and OR gates computes a monotone function, by induction along a topological order: the inputs are monotone, and AND and OR of monotone functions are monotone, since they are monotone in each argument. NOT is not monotone, so no such circuit computes it.

Exercise 27.11 ★★★

Prove that in the simulator’s model the nn-bit ripple-carry adder has delay 2n+12n + 1 for n≥1n \geq 1, and the lookahead block delay 4.

Solution

Solution of Exercise 27.11.

In stage ii, pi=ai⊕bip_i = a_i \oplus b_i and aibia_i b_i have depth 1. Let did_i be the depth of the carry cic_i: d0=0d_0 = 0, and c1=a0b0+p0c0c_1 = a_0 b_0 + p_0 c_0 has depth 3. For i≥1i \geq 1, picip_i c_i has depth di+1≥4d_i + 1 \geq 4 and the OR di+2d_i + 2, so di=2i+1d_i = 2i + 1 for i≥1i \geq 1. The sums si=pi⊕cis_i = p_i \oplus c_i have depth at most di+1≤2nd_i + 1 \leq 2n, so the carry out, of depth 2n+12n + 1, is the longest. In a lookahead block, gig_i and pip_i have depth 1, every AND of them (and of c0c_0) depth 2, every carry, an OR, depth 3, and every sum depth 4.

Exercise 27.12 ★★★

Build a 4-bit array multiplier from AND gates and full adders, test it on all 256 inputs, and give its size and delay.

Solution

Solution of Exercise 27.12.

def multiplier(n=4):
    c = Circuit(*[f"a{i}" for i in range(n)], *[f"b{i}" for i in range(n)])
    zero = c.gate("AND", "a0", c.gate("NOT", "a0"))
    acc = [c.gate("AND", f"a{i}", "b0") for i in range(n)] + [zero] * n
    for j in range(1, n):  # add (a AND b_j) shifted j places
        row = [c.gate("AND", f"a{i}", f"b{j}") for i in range(n)]
        carry = zero
        for i in range(n):
            acc[i + j], carry = full_adder(c, acc[i + j], row[i], carry)
        acc[n + j] = carry
    for k, w in enumerate(acc):
        c.outputs[f"p{k}"] = w
    return c
An array multiplier code/bachelor-1/27-combinational-circuits/exercises/multiplier.py

The 16 partial products aibja_i b_j cost 16 AND gates; three rows of four full adders add them, row jj shifted jj places. The circuit has 78 gates, including two that make a constant 0, and delay 18; the test compares it with x×yx \times y on the 256 pairs.

27.7 Problem: An arithmetic unit from one kind of gate

Problem 27.1

Weekend problem — An arithmetic unit from one kind of gate

A factory makes only NAND gates. How many does a half adder need? The program tries every circuit of kk two-input NAND gates, for k=1,2,…k = 1, 2, \dots; each signal is kept as its truth table on the four rows, a number of four bits.

def search(k):
    """(number of circuits tried, first circuit found or None). A circuit is a list of
    gates, each a pair of earlier signals; a signal is a 4-bit truth table."""
    tried, found = 0, None

    def extend(signals, gates):
        nonlocal tried, found
        if len(gates) == k:
            tried += 1
            if found is None and set(TARGETS.values()) <= set(signals[2:]):
                found = list(gates)
            return
        for i, j in combinations_with_replacement(range(len(signals)), 2):
            out = ~(signals[i] & signals[j]) & 0b1111  # NAND on all four rows at once
            extend(signals + [out], gates + [(i, j)])

    extend([A, B], [])
    return tried, found
Listing 27.8. Every NAND circuit of kk gates code/bachelor-1/27-combinational-circuits/listings/min_nand.py
$ python min_nand.py
gates 1:      3 circuits, half adder: none
gates 2:     18 circuits, half adder: none
gates 3:    180 circuits, half adder: none
gates 4:   2700 circuits, half adder: none
gates 5:  56700 circuits, half adder: [(0, 1), (0, 2), (1, 2), (2, 2), (3, 4)]
Output 27.8. The number of circuits tried, and the first half adder found; signals 0 and 1 are aa and bb, signal i+2i + 2 the output of gate ii.

Part I — Functions and forms.

  1. Give the truth tables of the sum and the carry of a half adder.
  2. Write their canonical sums of products.
  3. Why are 0b0011 and 0b0101 the truth tables of aa and bb?
  4. How does \textasciitilde(x & y) & 0b1111 compute a NAND on the four rows at once?
  5. How many Boolean functions of two variables are there? How many can a single NAND gate of aa and bb compute?
  6. Why is a circuit of gates with no loop a combinational circuit?

Part II — Translations into NAND.

  1. Translate the carry abab into NAND gates, and count them.
  2. Translate the sum a⊕ba \oplus b with four NAND gates, and check it on the four rows.
  3. Read the circuit found for k=5k = 5 and explain each gate.
  4. Why may the two outputs share a gate?
  5. Translate a full adder into NAND gates by the same method, and count them.
  6. What happens to the delay when each gate is replaced by its NAND translation?

Part III — Adders and delays.

  1. Read the sizes and delays of Output 27.6.
  2. Why is the delay of the ripple-carry adder linear and that of a lookahead block constant?
  3. Why do 8-bit lookahead adders have delay 6, and 64-bit ones 34?
  4. How many inputs does the largest AND gate of a lookahead block have? What does that cost in hardware?
  5. How many cases does the exhaustive check of the 8-bit adders try, and why is that a proof for 8 bits?
  6. Why can the 64-bit adders not be checked the same way?

Part IV — The smallest half adder.

  1. Show that the number of circuits of kk gates is ∏i=0k−1(i+32)\prod_{i=0}^{k-1} \binom{i + 3}{2}, and check it against the output.
  2. Why may a gate take the same signal twice?
  3. Why do circuits with unused gates not spoil the search?
  4. Why does the search for k=4k = 4 prove that four gates are not enough?
  5. Could a gate with three inputs, or a circuit with loops, do better? Does the search say?
  6. State the named result, the half adder needs exactly five NAND gates.
Solution

Solution of Problem 27.1.

1. On the rows ab=00,01,10,11ab = 00, 01, 10, 11: the sum is 0,1,1,00, 1, 1, 0 and the carry 0,0,0,10, 0, 0, 1.

2. Sum a′b+ab′a'b + ab', carry abab.

3. Read from left to right, the digits of 0b0011 are the values of aa on the rows 00,01,10,1100, 01, 10, 11, and those of 0b0101 the values of bb.

4. & works on the four rows in parallel, \textasciitilde inverts every bit (of an integer with infinitely many leading bits, in Python), and & 0b1111 keeps the four rows.

5. 222=162^{2^2} = 16. One gate computes NAND(a,a)=a′\text{NAND}(a, a) = a', NAND(b,b)=b′\text{NAND}(b, b) = b' or NAND(a,b)\text{NAND}(a, b): three functions, the three circuits of one gate.

6. Each gate uses earlier signals only, so the circuit is a DAG, and its outputs are functions of its inputs.

7. ab=NAND(n,n)ab = \text{NAND}(n, n) with n=NAND(a,b)n = \text{NAND}(a, b): two gates.

8. With n=NAND(a,b)n = \text{NAND}(a, b): NAND(NAND(a,n),NAND(b,n))\text{NAND}(\text{NAND}(a, n), \text{NAND}(b, n)). On 0000: n=1n = 1, both inner gates give 1, the result 0; on 0101 and 1010: n=1n = 1 and one inner gate gives 0, the result 1; on 1111: n=0n = 0, both inner gates give 1, the result 0.

9. Gate 0 is n=NAND(a,b)n = \text{NAND}(a, b); gates 1 and 2 are NAND(a,n)\text{NAND}(a, n) and NAND(b,n)\text{NAND}(b, n); gate 3 is NAND(n,n)=ab\text{NAND}(n, n) = ab, the carry; gate 4 combines gates 1 and 2 into a⊕ba \oplus b, the sum.

10. Both need NAND(a,b)\text{NAND}(a, b): computing it once saves a gate, 2+4−1=52 + 4 - 1 = 5.

11. Gate by gate: two XORs (4 each), two ANDs (2 each) and an OR (3), 15 NAND gates. Sharing, as in question 10, brings a full adder down to 9.

12. It grows: an AND becomes two levels, an OR two, an XOR three. NAND circuits are usually designed directly in two levels: a sum of products is a NAND of NANDs, by De Morgan.

13. 4 bits: 20 gates and delay 9 rippling, 26 gates and delay 4 with lookahead; 8 bits: 40 and 17 against 52 and 6.

14. Rippling, each carry waits for the one before: two gates per bit. Lookahead computes each carry of a block from the inputs by two levels of gates, whatever the block’s position.

15. Between blocks the carries still ripple: the carry out of block kk is ready two delays after its carry in. With n/4n / 4 blocks the last sums come at 2(n/4)+22(n / 4) + 2: 6 for 8 bits, 34 for 64.

16. Five: the term p3p2p1p0c0p_3 p_2 p_1 p_0 c_0 of c4c_4. Gates with many inputs need more transistors in series and are slower, so real designs limit them to about four inputs and use more levels.

17. 28×28×2=131 0722^8 \times 2^8 \times 2 = 131\,072: every possible input, so the check covers all behaviours of this circuit.

18. 21292^{129} inputs, beyond any computer: correctness for large nn needs a proof, by induction on the stages, as in Exercise 27.11.

19. Gate ii may use any unordered pair, repetitions allowed, of the i+2i + 2 signals before it: (i+32)\binom{i + 3}{2} choices. The products 33, 3×63 \times 6, ×10\times 10, ×15\times 15, ×21\times 21 are 3, 18, 180, 2700 and 56 700, as printed.

20. NAND(x,x)=x′\text{NAND}(x, x) = x': without it, NOT would need a constant input.

21. A circuit of j<kj < k useful gates, padded with k−jk - j more, is among the circuits of kk gates; extra gates do not change the signals already there.

22. Every circuit of at most four NAND gates appears among the 2700 tried (question 21), and none has both the sum and the carry among its signals.

23. The search says nothing about them: it covers loop-free circuits of two-input NAND gates, which is the claim.

24. The half adder needs exactly five NAND gates: a circuit of five computes it (question 9), and the exhaustive search over all 2901 circuits of one to four two-input NAND gates finds none.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো