কম্পিউটার বিজ্ঞান · বই 2 · শ্রেণি 10–12

High School Computer Science

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

High School Computer Science · শ্রেণি 10–12

12From Gates to an Arithmetic Unit

Book 1 ended its tour of logic gates with a half adder: two bits in, their sum and their carry out. A processor adds two numbers of 6464 bits each, billions of times a second, and it has no other material than such gates. This chapter builds the missing steps one at a time: an adder for three bits, an adder for whole numbers, a circuit that chooses, an arithmetic and logic unit with its flags, and finally a circuit that remembers. Each one is simulated in Python, gate by gate, and checked on every input.

You already know

A gate computes one bit from one or two bits: NOT, AND, OR, XOR, and NOR, which is NOT OR. A half adder computes a+ba + b for two bits: the sum bit is a⊕ba \oplus b and the carry is a∧ba \wedge b. De Morgan’s laws turn an AND into an OR of negations and back. A transistor works as a switch, which is how gates are built (Book 1, grade 9). On nn bits, two’s complement writes −x-x as 2n−x2^n - x (the chapter on numbers in binary).

The gates of the chapter are Python functions on the bits 00 and 11, in the module gates.py: NOT(a) returns 1−a1 - a, AND, OR and XOR use Python’s bitwise operators, and NOR(a, b) is NOT(OR(a, b)). Every circuit below is written with these five functions only.

A relay: an electromagnet that pulls metal contacts open or shut, a switch worked by a current. Machines such as the Harvard Mark II built their logic from relays before transistors replaced them (Book 1, grade 7). Photograph: Duncan Smith, public domain.
A relay: an electromagnet that pulls metal contacts open or shut, a switch worked by a current. Machines such as the Harvard Mark II built their logic from relays before transistors replaced them (Book 1, grade 7). Photograph: Duncan Smith, public domain.

12.1 The full adder

To add two numbers written in binary, each column adds three bits: the two digits of the column, and the carry from the column on its right. The half adder takes only two.

Definition 12.1 (Full adder)

A full adder is a circuit with three input bits aa, bb, cc and two output bits ss and c′c' such that a+b+c=2c′+sa + b + c = 2c' + s: ss is the sum bit, and c′c' the carry out.

A full adder is made of two half adders and an OR gate. The first half adder adds aa and bb, the second adds the carry cc to their sum bit, and since the two carries cannot both be 11, an OR combines them.

A full adder: two half adders and an OR gate, five gates in all. A dot marks where a wire branches; wires that cross without a dot are not connected.
A full adder: two half adders and an OR gate, five gates in all. A dot marks where a wire branches; wires that cross without a dot are not connected.
from gates import AND, OR, XOR


def half_adder(a, b):
    """Two bits in; their sum bit and their carry out."""
    return XOR(a, b), AND(a, b)


def full_adder(a, b, c):
    """Three bits in (c is the carry from the column before); sum and carry out."""
    s1, c1 = half_adder(a, b)
    s, c2 = half_adder(s1, c)
    return s, OR(c1, c2)


if __name__ == "__main__":
    print("a b c | s carry | a+b+c")
    for a in (0, 1):
        for b in (0, 1):
            for c in (0, 1):
                s, carry = full_adder(a, b, c)
                assert 2 * carry + s == a + b + c   # checked on all 8 rows
                print(f"{a} {b} {c} | {s}   {carry}   |   {a + b + c}")
Listing 12.1. The full adder, checked on its eight rows. code/grade-11/01-gates-to-arithmetic-unit/listings/full_adder.py
$ python full_adder.py
a b c | s carry | a+b+c
0 0 0 | 0   0   |   0
0 0 1 | 1   0   |   1
0 1 0 | 1   0   |   1
0 1 1 | 0   1   |   2
1 0 0 | 1   0   |   1
1 0 1 | 0   1   |   2
1 1 0 | 0   1   |   2
1 1 1 | 1   1   |   3
Output 12.1. The truth table: the two outputs, read as a binary number c′sc's, are a+b+ca + b + c.

Eight rows are all the inputs there are, so the assert of line 22 proves the circuit correct: an exhaustive check. A circuit whose outputs depend only on its present inputs, as here, is called combinational.

Definition 12.2 (Combinational and sequential circuits)

A combinational circuit computes its outputs from its present inputs only: the same inputs always give the same outputs. A sequential circuit also depends on what happened before, because some of its outputs are fed back to its inputs: it has a memory.

12.2 Chaining adders

Definition 12.3 (Ripple-carry adder)

A ripple-carry adder on nn bits is a row of nn full adders, one per column: the adder of column ii adds aia_i, bib_i and the carry cic_i from column i−1i - 1, and passes its carry out ci+1c_{i+1} to column i+1i + 1. The first carry c0c_0 is an input, usually 00; the last, cnc_n, is the carry out of the sum.

A 4-bit ripple-carry adder, drawn with the least significant column on the right, as numbers are written. The carry chain, in red, crosses every full adder: column 3 cannot finish before column 0 has.
A 44-bit ripple-carry adder, drawn with the least significant column on the right, as numbers are written. The carry chain, in red, crosses every full adder: column 33 cannot finish before column 00 has.

The simulation keeps the bits of a number in a list, least significant first, so that index ii is the column of weight 2i2^i.

from full_adder import full_adder


def to_bits(x, n):
    """The n bits of x, least significant first."""
    return [(x >> i) & 1 for i in range(n)]


def from_bits(bits):
    return sum(bit << i for i, bit in enumerate(bits))


def add_bits(a, b, carry=0):
    """Ripple-carry addition: one full adder per column, the carry passed along."""
    out = []
    carries = [carry]
    for x, y in zip(a, b):
        s, carry = full_adder(x, y, carry)
        out.append(s)
        carries.append(carry)
    return out, carries


if __name__ == "__main__":
    for x, y in [(100, 27), (200, 100), (100, 100)]:
        bits, carries = add_bits(to_bits(x, 8), to_bits(y, 8))
        result = from_bits(bits)
        overflow = carries[7] != carries[8]   # carry into bit 7 differs from carry out
        print(f"{x:3} + {y:3} = {result:3}  carry out {carries[8]}"
              f"  signed overflow {int(overflow)}  carries {carries[::-1]}")
Listing 12.2. An 88-bit adder from eight full adders. code/grade-11/01-gates-to-arithmetic-unit/listings/ripple.py
$ python ripple.py
100 +  27 = 127  carry out 0  signed overflow 0  carries [0, 0, 0, 0, 0, 0, 0, 0, 0]
200 + 100 =  44  carry out 1  signed overflow 0  carries [1, 1, 0, 0, 0, 0, 0, 0, 0]
100 + 100 = 200  carry out 0  signed overflow 1  carries [0, 1, 1, 0, 0, 1, 0, 0, 0]
Output 12.2. The carries are printed from c8c_8 down to c0c_0, in the order of the bits.

The second sum, 200+100=300200 + 100 = 300, does not fit in 88 bits: the result is 300−256=44300 - 256 = 44 and the carry out is 11, which signals the overflow for numbers read without sign. The third sum fits without sign, 200200, but read in two’s complement, 100+100100 + 100 gives −56-56, a sign change no correct sum of two positive numbers can have. A signed overflow happens exactly when the carry into the last column differs from the carry out of it, which is what line 28 computes.

The same adder subtracts. Flipping every bit of bb gives 2n−1−b2^n - 1 - b; adding 11 gives 2n−b2^n - b, the two’s complement of bb. So a−ba - b is a+b‾+1a + \overline{b} + 1, modulo 2n2^n, and the +1+1 costs nothing: it enters as the first carry c0c_0.

from gates import NOT
from ripple import add_bits, from_bits, to_bits


def sub_bits(a, b):
    """a - b with the same adder: a + (b with every bit flipped) + 1."""
    return add_bits(a, [NOT(bit) for bit in b], carry=1)


for x, y in [(100, 27), (27, 100), (5, 5)]:
    bits, carries = sub_bits(to_bits(x, 8), to_bits(y, 8))
    r = from_bits(bits)
    signed = r - 256 if bits[7] else r
    print(f"{x:3} - {y:3} -> {r:3} (as a signed byte {signed:4})"
          f"  carry out {carries[8]}")
Listing 12.3. Subtraction through the adder: flip, and carry in 11. code/grade-11/01-gates-to-arithmetic-unit/listings/subtract.py
$ python subtract.py
100 -  27 ->  73 (as a signed byte   73)  carry out 1
 27 - 100 -> 183 (as a signed byte  -73)  carry out 0
  5 -   5 ->   0 (as a signed byte    0)  carry out 1
Output 12.3. The carry out of a subtraction is 11 exactly when a≥ba \ge b: when it is 00, the subtraction needed a borrow.

12.3 Choosing and decoding

A processor computes several things at once and keeps one; it also has to turn a number, such as the number of a register, into one wire among several. Two small circuits do these jobs.

Definition 12.4 (Multiplexer, decoder)

A multiplexer with kk select bits has 2k2^k data inputs and one output, equal to the data input whose number is written by the select bits. A decoder with kk input bits has 2k2^k outputs, of which exactly one is 11: the one whose number is written by the inputs.

The 2:12{:}1 multiplexer is (¬s∧x0)∨(s∧x1)(\neg s \wedge x_0) \vee (s \wedge x_1): when s=0s = 0 the first AND lets x0x_0 through and the second gives 00, and the reverse when s=1s = 1. Three of them make a 4:14{:}1 multiplexer.

A 4:1 multiplexer from three 2:1 multiplexers. The bit s_0 chooses within each pair, then s_1 chooses between the pairs: the output is x_2s_1 + s_0.
A 4:14{:}1 multiplexer from three 2:12{:}1 multiplexers. The bit s0s_0 chooses within each pair, then s1s_1 chooses between the pairs: the output is x2s1+s0x_{2s_1 + s_0}.
from gates import AND, NOT, OR


def mux2(s, x0, x1):
    """x0 if s is 0, x1 if s is 1."""
    return OR(AND(NOT(s), x0), AND(s, x1))


def mux4(s1, s0, x):
    """One of the four inputs x[0..3], chosen by the two bits s1 s0."""
    return mux2(s1, mux2(s0, x[0], x[1]), mux2(s0, x[2], x[3]))


def decoder2(s1, s0):
    """Four outputs; exactly the one numbered s1 s0 is 1."""
    n1, n0 = NOT(s1), NOT(s0)
    return [AND(n1, n0), AND(n1, s0), AND(s1, n0), AND(s1, s0)]


if __name__ == "__main__":
    x = [0, 1, 1, 0]
    print("inputs x0..x3 =", x)
    for s1 in (0, 1):
        for s0 in (0, 1):
            print(f"select {s1}{s0}: mux4 -> {mux4(s1, s0, x)}"
                  f"   decoder -> {decoder2(s1, s0)}")
Listing 12.4. Multiplexers and a 22-to-44 decoder. code/grade-11/01-gates-to-arithmetic-unit/listings/mux.py
$ python mux.py
inputs x0..x3 = [0, 1, 1, 0]
select 00: mux4 -> 0   decoder -> [1, 0, 0, 0]
select 01: mux4 -> 1   decoder -> [0, 1, 0, 0]
select 10: mux4 -> 1   decoder -> [0, 0, 1, 0]
select 11: mux4 -> 0   decoder -> [0, 0, 0, 1]
Output 12.4. The multiplexer copies the chosen input; the decoder lights the chosen output.

12.4 An arithmetic and logic unit

Definition 12.5 (Arithmetic and logic unit)

An arithmetic and logic unit (ALU) is a combinational circuit with two numbers AA and BB as inputs and an operation code; it outputs the result of the chosen operation, and some flags about that result.

Definition 12.6 (Flag)

A flag is a bit that an operation sets to describe its result, for the instructions that follow to test. The toy machine of Book 1 has three: ZZ is 11 when the result is 00; NN is the last bit of the result, 11 when it is negative in two’s complement; CC is the carry out of an addition, and for a subtraction, 11 when it needed a borrow; logic operations set CC to 00.

The usual drawing of an ALU: two numbers enter at the top, the result leaves at the bottom, the operation code comes from the side, and the flags leave on the other side.
The usual drawing of an ALU: two numbers enter at the top, the result leaves at the bottom, the operation code comes from the side, and the flags leave on the other side.

The ALU below has four operations, coded on two bits: AND 0000, OR 0101, ADD 1010, SUB 1111. Each column computes the AND, the OR and the sum of its bits; a 4:14{:}1 multiplexer per column keeps the one the code asks for. For SUB, both code bits are 11: an AND of them flips bb through an XOR, and the low code bit is the first carry, which adds the 11 of the subtraction.

from full_adder import full_adder
from gates import AND, NOT, OR, XOR
from mux import mux4
from ripple import from_bits, to_bits

OPS = {"AND": (0, 0), "OR": (0, 1), "ADD": (1, 0), "SUB": (1, 1)}


def alu(op, a, b):
    """8-bit ALU: every column computes all four results, a multiplexer keeps one."""
    s1, s0 = OPS[op]
    carry = s0  # SUB adds 1 through the first carry
    out = []
    for x, y in zip(a, b):
        y2 = XOR(y, AND(s1, s0))  # flip b only for SUB
        s, carry = full_adder(x, y2, carry)
        out.append(mux4(s1, s0, [AND(x, y), OR(x, y), s, s]))
    zero = NOT(OR(OR(OR(out[0], out[1]), OR(out[2], out[3])),
                  OR(OR(out[4], out[5]), OR(out[6], out[7]))))
    c = AND(s1, XOR(carry, s0))  # ADD: the carry; SUB: no carry means a borrow
    return out, {"Z": zero, "N": out[7], "C": c}


if __name__ == "__main__":
    for op, x, y in [("AND", 12, 10), ("OR", 12, 10), ("ADD", 250, 10),
                     ("SUB", 5, 10), ("SUB", 10, 10)]:
        bits, flags = alu(op, to_bits(x, 8), to_bits(y, 8))
        print(f"{op:3} {x:3} {y:3} -> {from_bits(bits):3}  {flags}")
Listing 12.5. An 88-bit ALU with four operations and three flags. code/grade-11/01-gates-to-arithmetic-unit/listings/alu.py
$ python alu.py
AND  12  10 ->   8  {'Z': 0, 'N': 0, 'C': 0}
OR   12  10 ->  14  {'Z': 0, 'N': 0, 'C': 0}
ADD 250  10 ->   4  {'Z': 0, 'N': 0, 'C': 1}
SUB   5  10 -> 251  {'Z': 0, 'N': 1, 'C': 1}
SUB  10  10 ->   0  {'Z': 1, 'N': 0, 'C': 0}
Output 12.5. 5−105 - 10 gives 251251, which is −5-5 in two’s complement: N=1N = 1, and C=1C = 1 for the borrow.

The flag ZZ is a NOR of all eight result bits, built as a tree of ORs and one NOT. The flag CC inverts the carry out for a subtraction, so that it means “borrow” as on the toy machine, and is forced to 00 by the AND with the high code bit for the logic operations. The chapter’s tests run every operation of this ALU on 305305 pairs of numbers and compare the result and the three flags with the toy machine’s own instructions: they agree on all of them.

In practice — Faster carries

A ripple-carry adder is small but slow, since the carry crosses every column. Real processors use adders that compute the carries of a group of columns at once, from the signals g=a∧bg = a \wedge b (the column generates a carry) and p=a⊕bp = a \oplus b (it propagates one), at the price of more gates. The weekend problem measures one such idea.

12.5 A circuit that remembers

Everything so far forgets its inputs as soon as they change. A register must keep a number after the wires that brought it have moved on. The trick is to feed outputs back to inputs.

An SR latch: two NOR gates, each fed by the other’s output. S sets Q to 1, R resets it to 0, and with both at 0 the latch keeps the value it had.
An SR latch: two NOR gates, each fed by the other’s output. SS sets QQ to 11, RR resets it to 00, and with both at 00 the latch keeps the value it had.

Definition 12.7 (Latch, flip-flop)

A latch is a sequential circuit that keeps one bit: the SR latch is set to 11 by its input SS, reset to 00 by its input RR, and keeps its bit while both are 00. A flip-flop keeps one bit too, but changes it only at a precise moment: the D flip-flop copies its input DD to its output QQ at each rising edge of a clock signal, when the clock goes from 00 to 11, and ignores DD the rest of the time.

The simulation updates both gates at once from their previous outputs, again and again, until nothing changes.

from gates import NOR


def settle(s, r, q, qbar, steps=4):
    """Update both NOR gates at once, again and again, until nothing changes."""
    seen = [(q, qbar)]
    for _ in range(steps):
        q, qbar = NOR(r, qbar), NOR(s, q)
        if (q, qbar) == seen[-1]:
            return seen, True  # stable: the latch holds this state
        seen.append((q, qbar))
    return seen, False


q, qbar = 0, 1
for s, r, what in [(1, 0, "set"), (0, 0, "hold"), (0, 1, "reset"), (0, 0, "hold"),
                   (1, 1, "both"), (0, 0, "release")]:
    seen, stable = settle(s, r, q, qbar)
    q, qbar = seen[-1]
    end = f"Q={q}" if stable else "never settles"
    print(f"S={s} R={r} {what:8} {seen}  ->  {end}")
Listing 12.6. The SR latch, run until it settles. code/grade-11/01-gates-to-arithmetic-unit/listings/latch.py
$ python latch.py
S=1 R=0 set      [(0, 1), (0, 0), (1, 0)]  ->  Q=1
S=0 R=0 hold     [(1, 0)]  ->  Q=1
S=0 R=1 reset    [(1, 0), (0, 0), (0, 1)]  ->  Q=0
S=0 R=0 hold     [(0, 1)]  ->  Q=0
S=1 R=1 both     [(0, 1), (0, 0)]  ->  Q=0
S=0 R=0 release  [(0, 0), (1, 1), (0, 0), (1, 1), (0, 0)]  ->  never settles
Output 12.6. The latch remembers through each hold. After S=R=1S = R = 1, releasing both at once leaves it oscillating.

With S=R=1S = R = 1 both outputs are 00, so Q‾\overline{Q} is no longer the opposite of QQ; if both inputs then drop at once, both gates see two zeros and switch to 11, then both see a 11 and switch back, and so on. A real circuit does not oscillate for ever: one gate is always slightly faster, and the latch ends in a state that cannot be predicted. This is why S=R=1S = R = 1 is forbidden.

A D flip-flop is built from latches, in a way this book does not need: its behaviour is what matters. A register of nn bits is nn flip-flops that share the same clock.

class DFlipFlop:
    """Copies its input D to its output Q at a rising edge of the clock, only then."""

    def __init__(self):
        self.q = 0
        self.clock = 0

    def update(self, d, clock):
        if self.clock == 0 and clock == 1:  # rising edge
            self.q = d
        self.clock = clock


register = [DFlipFlop() for _ in range(4)]  # a 4-bit register
inputs = [0b0101, 0b0101, 0b1100, 0b1100, 0b1111, 0b0011, 0b0011, 0b1000]
clocks = [0, 1, 1, 0, 0, 1, 0, 1]
for t, (d, clock) in enumerate(zip(inputs, clocks)):
    for i, ff in enumerate(register):
        ff.update((d >> i) & 1, clock)
    q = sum(ff.q << i for i, ff in enumerate(register))
    print(f"t={t}  D={d:04b}  clock={clock}  Q={q:04b}")
Listing 12.7. A 44-bit register of D flip-flops, described by their behaviour. code/grade-11/01-gates-to-arithmetic-unit/listings/dff_register.py
$ python dff_register.py
t=0  D=0101  clock=0  Q=0000
t=1  D=0101  clock=1  Q=0101
t=2  D=1100  clock=1  Q=0101
t=3  D=1100  clock=0  Q=0101
t=4  D=1111  clock=0  Q=0101
t=5  D=0011  clock=1  Q=0011
t=6  D=0011  clock=0  Q=0011
t=7  D=1000  clock=1  Q=1000
Output 12.7. QQ changes only at t=1t = 1, 55 and 77, the rising edges: the input 11001100 at t=2t = 2 and 33 is never stored.

Remark 12.8

A processor is these pieces put together: registers of flip-flops hold the numbers, an ALU computes from two of them, multiplexers and decoders choose which, and the clock makes every flip-flop take its new value at the same moment, once the slowest path through the combinational circuits has settled. The length of that path fixes how fast the clock may beat; the next chapter assembles the whole machine.

12.6 Exercises

Exercise 12.1 ★

Give the outputs of the full adder for a=1a = 1, b=0b = 0, c=1c = 1, and the values of pp and gg in the figure of the full adder.

Solution

Solution of Exercise 12.1.

p=1⊕0=1p = 1 \oplus 0 = 1 and g=1∧0=0g = 1 \wedge 0 = 0; then s=p⊕c=0s = p \oplus c = 0 and the second carry is p∧c=1p \wedge c = 1, so c′=0∨1=1c' = 0 \vee 1 = 1. Indeed 1+0+1=21 + 0 + 1 = 2, written 1010.

Exercise 12.2 ★

Add 01110111 and 01100110 through a 44-bit ripple-carry adder, column by column: list the carries c0c_0 to c4c_4 and the sum bits.

Solution

Solution of Exercise 12.2.

c0=0c_0 = 0. Column 00: 1+0+0=11 + 0 + 0 = 1, so s0=1s_0 = 1, c1=0c_1 = 0. Column 11: 1+1+0=21 + 1 + 0 = 2, so s1=0s_1 = 0, c2=1c_2 = 1. Column 22: 1+1+1=31 + 1 + 1 = 3, so s2=1s_2 = 1, c3=1c_3 = 1. Column 33: 0+0+1=10 + 0 + 1 = 1, so s3=1s_3 = 1, c4=0c_4 = 0. The sum is 11011101, that is 7+6=137 + 6 = 13.

Exercise 12.3 ★

The inputs of a 4:14{:}1 multiplexer are x0=1x_0 = 1, x1=0x_1 = 0, x2=0x_2 = 0, x3=1x_3 = 1. What is the output for each of the four values of s1s0s_1 s_0?

Solution

Solution of Exercise 12.3.

s1s0=00s_1 s_0 = 00 gives x0=1x_0 = 1, 0101 gives x1=0x_1 = 0, 1010 gives x2=0x_2 = 0, 1111 gives x3=1x_3 = 1.

Exercise 12.4 ★

A decoder has 33 input bits. How many outputs does it have, and which one is 11 when the inputs are 101101?

Solution

Solution of Exercise 12.4.

23=82^3 = 8 outputs, numbered 00 to 77; for 101101 the output number 55 is 11 and the seven others are 00.

Exercise 12.5 ★

Write half_adder(a, b) using only NOT, AND and OR, and check it on its four rows.

Solution

Solution of Exercise 12.5.

The carry is AND(a, b); the sum is 11 when at least one input is 11 but not both, so it is AND(OR(a, b), NOT(AND(a, b))). The file exercises/circuits.py has it, and the tests check the four rows.

Exercise 12.6 ★★

In a full adder, the first half adder was built with an AND gate where its XOR should be. On which of the eight rows is the result wrong? Which test of the chapter would find it?

Solution

Solution of Exercise 12.6.

Six rows are wrong: every row except 000000 and 001001. With an AND, the first “sum” is 11 only when a=b=1a = b = 1, so it is wrong whenever exactly one of aa, bb is 11 (four rows); and when a=b=1a = b = 1, the first “sum” is 11 instead of 00, so the sum bit becomes 1⊕c1 \oplus c, the opposite of cc, wrong in both rows (the carry, abab, stays right). The assert of full_adder.py, which tries all eight rows, stops at the third, 010010.

Exercise 12.7 ★★

Write mux4(sel, inputs), where sel is a whole number from 00 to 33 and inputs a list of four bits, using mux2 only.

Solution

Solution of Exercise 12.7.

Split sel into its two bits, then choose within each pair and between the pairs:

s1, s0 = (sel >> 1) & 1, sel & 1

low = mux2(s0, inputs[0], inputs[1])

high = mux2(s0, inputs[2], inputs[3])

and the result is mux2(s1, low, high). The file exercises/circuits.py writes the three calls as one expression.

Exercise 12.8 ★★

How many gates does an nn-bit ripple-carry adder have? How many if the first column, whose carry in is always 00, uses a half adder?

Solution

Solution of Exercise 12.8.

Five gates per full adder: 5n5n. With a half adder (two gates) in the first column: 5(n−1)+2=5n−35(n - 1) + 2 = 5n - 3.

Exercise 12.9 ★★

Count the gates a signal crosses from the carry cic_i to the carry ci+1c_{i+1} in the figure of the full adder. Deduce the length of the longest chain of gates in an nn-bit ripple-carry adder, assuming all the inputs are ready at the start.

Solution

Solution of Exercise 12.9.

From cic_i to ci+1c_{i+1} the signal crosses the AND of the second half adder and the OR: 22 gates. In column 00, the carry c1c_1 needs the XOR, then an AND, then the OR: level 33. Each later column adds 22, so cnc_n is ready at level 3+2(n−1)=2n+13 + 2(n - 1) = 2n + 1, and that is the longest chain. For 6464 bits, 129129 gates.

Exercise 12.10 ★★

A subtraction circuit flips the bits of bb but leaves the first carry at 00. What does it compute for 100−27100 - 27? In general?

Solution

Solution of Exercise 12.10.

It computes a+b‾=a+(2n−1−b)a + \overline{b} = a + (2^n - 1 - b), that is a−b−1a - b - 1 modulo 2n2^n: 100−27100 - 27 gives 7272 instead of 7373. Every result is one too small.

Exercise 12.11 ★★

Write alu_reference(op, x, y), which computes the same result and flags as the ALU with Python’s integer operators instead of gates. Why is such a second version useful?

Solution

Solution of Exercise 12.11.

For ADD, the result is (x + y) % 256 and CC is int(x + y > 255); for SUB, (x - y) % 256 and int(x < y); ZZ is int(r == 0) and NN is r >> 7 (exercises/circuits.py). Two versions written in very different ways rarely make the same mistake: comparing them on many inputs finds the mistakes of either. The tests compare the gate ALU with this one and with the toy machine.

Exercise 12.12 ★★★

From the truth table of the full adder, prove that s=a⊕b⊕cs = a \oplus b \oplus c and that c′=(a∧b)∨(c∧(a⊕b))c' = (a \wedge b) \vee (c \wedge (a \oplus b)), then that c′c' is also (a∧b)∨(b∧c)∨(a∧c)(a \wedge b) \vee (b \wedge c) \vee (a \wedge c): the carry is 11 when at least two inputs are.

Solution

Solution of Exercise 12.12.

The table shows s=1s = 1 exactly on the rows with one or three ones, an odd number; a⊕ba \oplus b is 11 when a+ba + b is odd, and XOR with cc flips that when c=1c = 1, so a⊕b⊕ca \oplus b \oplus c is 11 exactly when a+b+ca + b + c is odd: s=a⊕b⊕cs = a \oplus b \oplus c. The table shows c′=1c' = 1 exactly on the rows 011011, 101101, 110110, 111111, those with at least two ones. The term a∧ba \wedge b is 11 on 110110 and 111111; the term c∧(a⊕b)c \wedge (a \oplus b) on 011011 and 101101; their OR is 11 on these four rows and no other. The three terms a∧ba \wedge b, b∧cb \wedge c, a∧ca \wedge c say “these two are 11”, and their OR is 11 exactly when at least two inputs are: the same four rows.

Exercise 12.13 ★★★

Let b‾\overline{b} be bb with its nn bits flipped. Prove that b‾=2n−1−b\overline{b} = 2^n - 1 - b, then that a+b‾+1≡a−b(mod2n)a + \overline{b} + 1 \equiv a - b \pmod{2^n}, and that the carry out of this sum is 11 exactly when a≥ba \ge b.

Solution

Solution of Exercise 12.13.

Bit ii of b‾\overline{b} is 1−bi1 - b_i, so b‾=∑i(1−bi)2i=(2n−1)−b\overline{b} = \sum_i (1 - b_i) 2^i = (2^n - 1) - b. Then a+b‾+1=a−b+2na + \overline{b} + 1 = a - b + 2^n, which is a−ba - b modulo 2n2^n. The adder keeps nn bits, and its carry out is 11 exactly when the true sum a−b+2na - b + 2^n is at least 2n2^n, that is when a≥ba \ge b.

Exercise 12.14 ★★★

Write comparator(x, y), which returns "<", "=" or ">" for two numbers without sign, using only the result and the carry out of the subtraction circuit.

Solution

Solution of Exercise 12.14.

Subtract yy from xx. If the result is 00, "="; otherwise, a carry out of 00 means a borrow, so x<yx < y and the answer is "<"; a carry out of 11 means x>yx > y (exercises/circuits.py). These are the flags ZZ and CC of the instruction CMP of the toy machine.

Exercise 12.15 ★★★

Trace the SR latch by hand, both gates updated at once, from Q=0Q = 0, Q‾=1\overline{Q} = 1: first S=R=1S = R = 1 until it settles, then S=R=0S = R = 0. Then trace the same release when the gate of QQ is faster, so that it updates first. Explain why the inputs S=R=1S = R = 1 are forbidden.

Solution

Solution of Exercise 12.15.

With S=R=1S = R = 1, from (Q,Q‾)=(0,1)(Q, \overline{Q}) = (0, 1): both NORs see a 11, so the next state is (0,0)(0, 0), and it stays. Releasing both at once, each gate sees two zeros: (1,1)(1, 1); then each sees a 11: (0,0)(0, 0); and so on for ever, as the output of latch.py shows. If the gate of QQ is faster, it switches first to Q=NOR(0,0)=1Q = \text{NOR}(0, 0) = 1; the other gate then sees Q=1Q = 1 and stays at 00: the latch ends at Q=1Q = 1. If the other gate is faster, it ends at Q=0Q = 0. The final state depends on which gate is faster, which nobody controls; and while S=R=1S = R = 1, Q‾\overline{Q} is not the opposite of QQ. Both are reasons to forbid these inputs.

12.7 Problem: Building a 64-Bit Adder

Problem 12.1

Weekend problem — the size and the speed of an adder

A processor adds numbers of 6464 bits. How many gates does its adder need, and how long is the longest chain of gates a signal must cross before the sum is ready? The program gate_count.py answers by running the adders of the chapter on levels instead of bits: each signal carries the number of gates it has crossed since the inputs.

"""Count the gates of an adder, and the longest chain of gates a signal goes through."""

count = 0


def gate(*inputs):
    """A gate seen from outside: its output is ready one level after its last input."""
    global count
    count += 1
    return max(inputs) + 1


def full_adder(a, b, c):  # the same five gates as full_adder.py, on levels
    p = gate(a, b)                      # XOR
    s = gate(p, c)                      # XOR
    carry = gate(gate(a, b), gate(p, c))  # OR of two ANDs
    return s, carry


def ripple(n, carry=0):
    sums = []
    for _ in range(n):
        s, carry = full_adder(0, 0, carry)  # the inputs are ready at level 0
        sums.append(s)
    return sums, carry


def carry_select(n):
    """The low half ripples; the high half is computed twice, for carry 0 and 1."""
    low, c = ripple(n // 2)
    high0, c0 = ripple(n // 2, 0)  # assuming carry 0
    high1, c1 = ripple(n // 2, 0)  # assuming carry 1: a constant too, at level 0
    not_c = gate(c)
    chosen = [gate(gate(not_c, x0), gate(c, x1))  # a 2:1 multiplexer per bit
              for x0, x1 in zip(high0 + [c0], high1 + [c1])]
    return low + chosen[:-1], chosen[-1]
Listing 12.8. Gates that count themselves and their levels, and two adders built from them. code/grade-11/01-gates-to-arithmetic-unit/listings/gate_count.py
$ python gate_count.py
   n | ripple: gates levels | carry-select: gates levels
   2 |            10      5 |                  22      6
   4 |            20      9 |                  40      8
   8 |            40     17 |                  76     12
  16 |            80     33 |                 148     20
  32 |           160     65 |                 292     36
  64 |           320    129 |                 580     68
Output 12.8. The count and the depth of the two adders.

Part I — One full adder.

  1. In gate_count.py, what does gate return, and why is the maximum of the inputs the right choice?
  2. Check that its full_adder uses the same five gates as the figure of the full adder.
  3. With all three inputs at level 00, at which level are ss and the carry out ready?
  4. With aa and bb at level 00 and the carry in at level k≥1k \ge 1, at which levels are ss and the carry out ready?

Part II — The ripple-carry adder.

  1. Show that the carry gains two levels at each column after the first, and deduce that cic_i is ready at level 2i+12i + 1, for i≥1i \ge 1.
  2. Deduce the level of the last sum bit and of the carry out, for nn bits, and check them against the output.
  3. How many gates for 88, 1616, 3232 and 6464 bits?
  4. If a gate takes 1010 picoseconds to switch, how long does a 6464-bit ripple-carry addition take, and how many such additions could follow each other in one second?
  5. Which part of the circuit decides that time: the sum bits or the carry chain?

Part III — Carry-select.

  1. The carry-select adder adds the low half with a ripple adder. Explain why the high half can be computed before the carry of the low half is known.
  2. Why is it computed twice, and how is the right copy chosen?
  3. In the program, how many 2:12{:}1 multiplexers are used for nn bits, and how many gates does each take?
  4. Compute the number of gates of the carry-select adder for nn bits, and check it for n=64n = 64.
  5. At which level is the carry of the low half ready, and at which level is the output of a multiplexer ready?
  6. Check the depth of 6868 for 6464 bits.

Part IV — Comparing.

  1. For 6464 bits, compute the ratio of the gates and the ratio of the levels of the two adders.
  2. Split the 6464 bits into four blocks of 1616 instead of two halves, each block after the first computed twice. Estimate its depth.
  3. Why do processors pay for more gates to save levels?
  4. Is there a limit to the speed-up? Describe the shortest adder you can imagine, and what it costs.
  5. State the result: the gates and levels of a 6464-bit ripple-carry adder, and what carry-select buys and costs.
Solution

Solution of Problem 12.1.

1. The level of its output: one more than the latest of its inputs, since a gate can only switch once all its inputs are there.

2. p is the XOR of aa and bb, s the XOR of p and cc, then two ANDs, of aa and bb and of p and cc, and the OR of these: five gates, as in the figure.

3. pp at 11, ss at 22; the ANDs at 11 and 22, the carry out at 33.

4. pp at 11, ss at k+1k + 1; the AND of aa and bb at 11, the AND of pp and cc at k+1k + 1, and the carry out at k+2k + 2.

5. By question 3, c1c_1 is at level 33; by question 4, a carry at level kk gives the next one at k+2k + 2. So c1,c2,c3,…c_1, c_2, c_3, \dots are at 3,5,7,…3, 5, 7, \dots: cic_i is at 2i+12i + 1.

6. The last sum bit sn−1s_{n-1} is at (2(n−1)+1)+1=2n(2(n - 1) + 1) + 1 = 2n, the carry out cnc_n at 2n+12n + 1. The output gives 55 for 22 bits and 129129 for 6464: 2n+12n + 1, the carry out being the last signal ready.

7. 5n5n: 4040, 8080, 160160 and 320320 gates.

8. 129×10129 \times 10 ps =1.29= 1.29 ns, so about 775775 million additions in a row per second.

9. The carry chain: each sum bit is ready one level after its carry, so the sums wait for the carries.

10. Its inputs, the high halves of AA and BB, are there from the start; only its carry in is missing, and that carry can only be 00 or 11.

11. Once assuming a carry of 00, once assuming 11; when the low half’s carry arrives, a multiplexer per output bit keeps the copy made with the right assumption.

12. One multiplexer per sum bit of the high half and one for the carry out: n/2+1n/2 + 1. Each takes two ANDs and an OR, and the NOT of the select signal is shared by all.

13. Three ripple adders of n/2n/2 bits, 3×5n/23 \times 5n/2 gates, plus 3(n/2+1)3(n/2 + 1) for the multiplexers and 11 NOT: 15n/2+3n/2+4=9n+415n/2 + 3n/2 + 4 = 9n + 4. For n=64n = 64, 580580, as printed.

14. The low half is a ripple adder of n/2n/2 bits: its carry is at level 2(n/2)+1=n+12(n/2) + 1 = n + 1. The high halves are ready earlier, at level n+1n + 1 at most. The NOT of the carry is at n+2n + 2, the AND that uses it at n+3n + 3, the OR at n+4n + 4.

15. 64+4=6864 + 4 = 68.

16. 580/320≈1.81580/320 \approx 1.81 times the gates, for 68/129≈0.5368/129 \approx 0.53 times the levels.

17. The first block of 1616 bits gives its carry at level 3333. The three other blocks are computed both ways in parallel, and ready at level 3333 too. Each multiplexer stage adds 33 levels to the chosen carry: 3636 after the second block, 3939 after the third, and the outputs of the last block at about 4242. The gates grow again, to about 5⋅16+3⋅2⋅5⋅16+3⋅3⋅17+3≈7165 \cdot 16 + 3 \cdot 2 \cdot 5 \cdot 16 + 3 \cdot 3 \cdot 17 + 3 \approx 716.

18. Every instruction must finish within one beat of the clock, so the slowest circuit sets the speed of the whole processor. Gates are tiny and cheap, counted in billions on one chip; time is not.

19. More blocks, and blocks inside blocks, reduce the depth further: adders used in processors make the depth grow much more slowly than the number of bits, so that doubling the bits adds only a few levels. The shortest imaginable adder writes each output as one OR of ANDs of the inputs, two levels deep, but the cost explodes: for the top carry of 6464 bits, the OR would need on the order of 2642^{64} AND terms, each with up to 128128 inputs. Speed always costs gates, and two levels cost exponentially many.

20. A 6464-bit ripple-carry adder needs 320320 gates, five per full adder, and its longest chain crosses 129129 gates, the carry gaining two levels per column. A carry-select adder of two halves needs 580580 gates, 1.811.81 times as many, and 6868 levels, 0.530.53 times as many: it nearly halves the delay for less than twice the gates.

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

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