Computer Arithmetic
Learn how to use Mealy machines to perform arithmetic operations like addition, subtraction, and rounding.
Mealy machines naturally model low-level computer arithmetic algorithms. A one’s-complement machine, for example, is modeled by the following trivial machine.
Adding two binary numbers
Adding two binary numbers is also “Mealy-able,” but requires reading corresponding bits simultaneously, right-to-left. The machine will therefore take pairs of bits as input, in reverse order. Recall how to add binary numbers by hand:
The Mealy machine below considers each vertical bit-pair from right-to-left, mimicking what we do manually. We assume it emits the result in right-to-left order.
Implementation of the carry
The one thing missing is the leftmost carry bit (only is printed for the sum above instead of ). To solve this problem, we assume that each state emits the bit in its label, which is the carry, when the machine halts there. The code below implements the carry.
def binadd(x,y):assert len(x) == len(y)state = "0"pairs = zip(x,y) # Combine strings pairwiseresult = ""for b1,b2 in reversed(pairs):if state == "0":if b1=="1" and b2=="0" or b1=="0" and b2=="1":result += "1"elif b1=="0" and b2=="0":result += "0"elif b1=="1" and b2== "1":result += "0"state = "1"else:assert False, "invalid input"else: # state == "1"if b1=="1" and b2=="0" or b1=="0" and b2=="1":result += "0"elif b1=="1" and b2=="1":result += "1"elif b1=="0" and b2== "0":result += "1"state = "0"else:assert False, "invalid input"if state == "1":result += "1" # Append carryreturn result[::-1] # Reverse resultprint(binadd("1101","0110")) # 10011
Code explanation
This code defines a function called binadd
, which takes in two strings, x
and y
, and performs a binary addition operation on them:
- In line 2, the
assert
command checks that the two input stringsx
andy
have the same length. If not, the program will raise anAssertionError