Boolean Algebra
โน๏ธ Why It Matters
Boolean algebra is the mathematics of logic and digital circuits. Every computer is built from logic gates implementing Boolean operations. Search engines use Boolean queries (AND, OR, NOT), databases use Boolean conditions in WHERE clauses, and machine learning decision trees make Boolean splits. Understanding Boolean algebra is essential for digital design, circuit optimization, search technology, and logical reasoning in AI.
Definitions
DfBoolean Algebra
Boolean algebra is an algebraic structure where , is OR, is AND, is NOT, and and are identity elements.
DfBoolean Expression
A Boolean expression combines variables, constants 0 and 1, and operations AND (), OR (), NOT () according to algebraic rules.
DfSum-of-Products (SOP)
A Boolean expression written as a sum (OR) of product (AND) terms: . Each product term is a minterm.
DfProduct-of-Sums (POS)
A Boolean expression written as a product (AND) of sum (OR) terms: . Each sum term is a maxterm.
DfDuality
The dual of a Boolean expression is obtained by swapping AND with OR, and 0 with 1, while keeping variables unchanged. The dual of a true identity is also true.
DfMinterm
A minterm is a product term containing every variable exactly once, either in true or complemented form. For variables, there are minterms.
DfMaxterm
A maxterm is a sum term containing every variable exactly once. For variables, there are maxterms.
Laws of Boolean Algebra
| Law | AND () | OR () |
|---|---|---|
| Identity | ||
| Null (Annihilator) | ||
| Idempotent | ||
| Complement | ||
| Commutative | ||
| Associative | ||
| Distributive | ||
| Absorption | ||
| De Morgan's | ||
| Double Complement |
Python Implementations
Truth Table Generator
from itertools import product
def truth_table(expression_func, variables):
n = len(variables)
header = variables + ["Result"]
print(" | ".join(f"{v:>6}" for v in header))
print("-" * (8 * len(header)))
for values in product([0, 1], repeat=n):
env = dict(zip(variables, values))
result = expression_func(**env)
row = [str(v) for v in values] + [str(int(result))]
print(" | ".join(f"{v:>6}" for v in row))
# Example: F = A AND (B OR NOT C)
truth_table(
lambda A, B, C: A & (B | (not C)),
['A', 'B', 'C']
)
Boolean Simplification
def boolean_simplify_sop(minterms, variables):
"""Convert minterms to SOP expression."""
terms = []
for m in minterms:
term = []
for i, v in enumerate(variables):
if m & (1 << (len(variables) - 1 - i)):
term.append(v)
else:
term.append(f"{v}'")
terms.append("".join(term))
return " + ".join(terms)
def boolean_simplify_pos(maxterms, variables):
"""Convert maxterms to POS expression."""
terms = []
for m in maxterms:
term = []
for i, v in enumerate(variables):
if m & (1 << (len(variables) - 1 - i)):
term.append(f"{v}'")
else:
term.append(v)
terms.append("(" + " + ".join(term) + ")")
return " * ".join(terms)
# SOP for F(A,B,C) = sum of minterms 1, 3, 5, 7
print(boolean_simplify_sop([1, 3, 5, 7], ['A', 'B', 'C']))
# Output: A'B'C + A'BC + AB'C + ABC
Karnaugh Map
def karnaugh_map_4var(minterms):
"""Print K-map for 4-variable function."""
# K-map ordering: 00, 01, 11, 10
order = [0, 1, 3, 2]
map = [[0] * 4 for _ in range(4)]
for m in minterms:
row = (m >> 2) & 3
col = m & 3
ri = order.index(row)
ci = order.index(col)
map[ri][ci] = 1
print(" AB\\CD 00 01 11 10")
labels = ['00', '01', '11', '10']
for i, label in enumerate(labels):
row_str = " ".join(f" {map[i][j]} " for j in range(4))
print(f" {label} {row_str}")
return map
# Example: F(A,B,C,D) = sum of minterms 0,1,2,5,6,7,8,9,10,14
karnaugh_map_4var([0, 1, 2, 5, 6, 7, 8, 9, 10, 14])
Logic Gate Simulation
def AND(a, b):
return a & b
def OR(a, b):
return a | b
def NOT(a):
return 1 - a
def NAND(a, b):
return NOT(AND(a, b))
def NOR(a, b):
return NOT(OR(a, b))
def XOR(a, b):
return AND(OR(a, b), NAND(a, b))
def XNOR(a, b):
return NOT(XOR(a, b))
# Half adder
def half_adder(a, b):
s = XOR(a, b)
c = AND(a, b)
return s, c
# Full adder
def full_adder(a, b, cin):
s1, c1 = half_adder(a, b)
s, c2 = half_adder(s1, cin)
cout = OR(c1, c2)
return s, cout
# Test
for a in range(2):
for b in range(2):
s, c = half_adder(a, b)
print(f"{a} + {b} = {c}{s}")
Karnaugh Maps
โน๏ธ Karnaugh Map Method
Karnaugh maps provide a visual method for simplifying Boolean expressions:
- Draw a grid with rows and columns for variables
- Label rows and columns using Gray code order (adjacent cells differ by 1 bit)
- Place 1s in cells corresponding to minterms where
- Group adjacent 1s in rectangles of size (powers of 2)
- Each group gives one product term: variables that don't change within the group are kept
- The minimal SOP is the OR of all group terms
Grouping rules:
- Groups must be rectangular with cells
- Groups may wrap around edges
- Groups may overlap
- Use the fewest groups possible (each group as large as possible)
Applications in AI/ML
โน๏ธ Applications in AI and Machine Learning
- Decision Trees: Each internal node tests a Boolean condition; splits are Boolean expressions
- Search Engines: Boolean queries combine terms with AND, OR, NOT for document retrieval
- Database Queries: WHERE clauses use Boolean predicates for filtering
- Circuit Design: Digital circuits implement Boolean functions with logic gates
- Logic Programming: Prolog and Datalog use Boolean logic for rule evaluation
- Formal Verification: Model checking verifies Boolean properties of hardware/software
- Constraint Satisfaction: Boolean satisfiability (SAT) is NP-complete but has efficient solvers for many practical instances
- Neural Networks: Threshold logic units implement Boolean functions
Common Mistakes
| Mistake | Correction |
|---|---|
| Confusing AND and OR distributive laws | , NOT |
| Forgetting De Morgan's laws | and |
| Ignoring self-duality | Swap AND/OR and 0/1 to get the dual; both are valid |
| Treating Boolean like regular algebra | (not ); (not ) |
| Confusing SOP and POS | SOP = sum of products (OR of ANDs); POS = product of sums (AND of ORs) |
| Not using Gray code for K-maps | Adjacent cells in K-maps must differ by exactly one bit |
| Assuming more terms = simpler | Fewer terms with fewer literals = simpler expression |
| Forgetting XOR is not a basic Boolean op | XOR can be expressed as |
Interview Questions
-
What are the three basic Boolean operations? AND (), OR (), and NOT (). All Boolean functions can be expressed using these three.
-
State De Morgan's laws. and . These convert between AND/OR through complementation.
-
What is the dual of a Boolean expression? Swap AND with OR and 0 with 1. The dual of a true identity is also true (Principle of Duality).
-
How do you simplify a Boolean expression? Use algebraic laws (absorption, distribution, De Morgan's) or Karnaugh maps for visual minimization.
-
What is a minterm and maxterm? A minterm is a product of all variables (each true or complemented); a maxterm is a sum. There are of each for variables.
-
What is the consensus theorem? . The term is redundant (consensus of and ).
-
How do Karnaugh maps work? Group adjacent 1s in powers of 2 on a Gray-coded grid. Each group becomes one product term. Larger groups = simpler expression.
-
What is functional completeness? A set of operations is functionally complete if any Boolean function can be expressed using only those operations. {AND, OR, NOT} and {NAND} and {NOR} are each functionally complete.
Practice Problems
๐Practice: Boolean Simplification
Problem: Simplify .
๐กSolution: Boolean Simplification
. The function is always true (tautology).
๐Practice: Karnaugh Map
Problem: Simplify using a K-map.
๐กSolution: Karnaugh Map
K-map groups: (covers m0, m1), (covers m1, m5), (covers m2, m6, m3, m7). Minimal SOP: .
๐Practice: De Morgan's
Problem: Apply De Morgan's to .
๐กSolution: De Morgan's
.
๐Practice: Gate Implementation
Problem: Implement XOR using only AND, OR, and NOT gates.
๐กSolution: Gate Implementation
. Requires two NOT gates, two AND gates, and one OR gate.
Quick Reference
| Operation | Symbol | Truth Table |
|---|---|---|
| AND | 1 only when both 1 | |
| OR | 1 when at least one 1 | |
| NOT | Flips the value | |
| XOR | 1 when different | |
| NAND | NOT of AND | |
| NOR | NOT of OR | |
| XNOR | 1 when same |
| Identity | Formula |
|---|---|
| Idempotent | , |
| Complement | , |
| Absorption | , |
| De Morgan's | , |
| Consensus |
Quine-McCluskey Method
โน๏ธ Quine-McCluskey Method
The Quine-McCluskey method is a tabular algorithm for Boolean minimization, guaranteed to find the minimal form (unlike K-maps which are limited to 6 variables):
- Group minterms by number of 1s
- Combine terms that differ in exactly one position
- Mark combined terms as used
- Find prime implicants (terms that cannot be combined further)
- Use a prime implicant chart to select the minimal set covering all minterms
def quine_mccluskey(minterms, num_vars):
def count_ones(n):
return bin(n).count('1')
def combine_terms(t1, t2):
diff = 0
pos = -1
for i in range(num_vars):
b1 = (t1 >> i) & 1
b2 = (t2 >> i) & 1
if b1 != b2:
diff += 1
pos = i
if diff == 1:
return t1 & ~(1 << pos)
return None
groups = {}
for m in minterms:
ones = count_ones(m)
groups.setdefault(ones, []).append([m])
prime_implicants = []
while groups:
new_groups = {}
used = set()
for g1 in sorted(groups.keys()):
for g2 in sorted(groups.keys()):
if g2 <= g1:
continue
for t1 in groups[g1]:
for t2 in groups[g2]:
combined = combine_terms(t1[0], t2[0])
if combined is not None:
new_terms = sorted(set(t1 + t2))
key = tuple(new_terms)
if key not in new_groups:
new_groups[key] = [new_terms]
else:
new_groups[key].append(new_terms)
used.add(t1[0])
used.add(t2[0])
for g in groups.values():
for t in g:
if t[0] not in used:
prime_implicants.append(t)
if not new_groups:
break
groups = {}
for key, terms in new_groups.items():
ones = count_ones(key[0])
groups.setdefault(ones, []).extend(terms)
return prime_implicants
# Example: minimize F(A,B,C) = sum(1, 2, 3, 5, 7)
pis = quine_mccluskey([1, 2, 3, 5, 7], 3)
print(f"Prime implicants: {[bin(p[0]) for p in pis]}")
Boolean Function Properties
| Property | Description |
|---|---|
| Self-dual | (function equals its dual) |
| Monotone | Increasing any input never decreases output |
| Linear | |
| Balanced | Outputs 0 and 1 equally often |
| Affine | Linear plus a constant |
Cross-References
- Graph Theory รขโฌโ Discrete Graphs: Graph coloring uses Boolean logic
- Trees รขโฌโ Discrete Trees: Tree traversals use Boolean conditions
- Number Theory รขโฌโ Discrete Number Theory: Finite field arithmetic
- Recurrence Relations รขโฌโ Discrete Recurrence: Boolean function complexity
- Automata Theory รขโฌโ Discrete Automata: State transitions use Boolean logic
- Applications รขโฌโ Discrete Applications: Digital circuits and logic design