integrated circuits place many components on one crystal
third generation: computers assembled from integrated circuits
increasing integration eventually puts a whole CPU on one chip
Intel 4004 is identified as the first commercially available microprocessor
book also discusses the competing historical claim concerning MP944
40
microprocessor -> affordable desktop / personal computer
book calls this the fourth generation
treats the Japanese fifth-generation project as a different software direction
41
computers process any information with a usable representation
texts, databases, sound, images and video
book discusses tactile devices and limitations of recording taste / smell
42
computation is broader than arithmetic
supercomputers still serve large numerical tasks
a mathematical function may map objects of arbitrary kinds
digital information becomes strings over an alphabet
-> information processing = computing a function from strings to strings
Processor, Memory, Bus
Component
Role
CPU
Execute instructions using registers
RAM
Addressable working memory; volatile
ROM / firmware
Retain startup code across power loss
Bus
Carry addresses, data, and read/write signals
Controller / driver
Hardware interface / software that controls it
OS
Protect and allocate memory; manage tasks, devices, and files
With
address bits, there are
possible addresses.
RAM is accessed through the memory bus; disks require a controller
and driver.
Detailed notes - 1.1.2: CPU, RAM, bus
1
bus: parallel lines carrying signals between components
address bus: which location / controller responds
data bus: transferred information
control bus: operation to perform
connected to CPU, RAM and external-device controllers
RAM / controllers respond only when their address is selected
2-3
RAM: uniform addressable memory locations
each location has its own address
N address lines -> 2^N possible addresses
these addresses form the physical address space
virtual address space: addresses presented to a program; introduced later
4-5
memory access: read or write
CPU selects address and sends operation signal
read: selected location places its value on data bus
write: selected location takes new value from data bus; old value lost
several adjacent locations can hold one value
RAM is volatile: contents disappear when power is removed
6
RAM != disk storage
CPU accesses RAM directly
disks require controller operations performed by driver programs
7-8
ROM: retains contents without power; ordinary CPU writes cannot change it
startup program checks hardware, finds and loads the OS
OS is a program:
receives privileged access and controls later programs
user programs work in allocated memory and request other actions from OS
drivers organize work with external devices
9
files: OS organization of information in long-term storage
names allow users to find saved information
RAM allocation changes with running programs
OS tracks assigned regions
each program accesses its own allocated memory
memory regions do not need user-facing file names
Clarification. Files are a filesystem abstraction:
they can also live in RAM or represent generated data. The disk-only
wording in these introductory notes describes persistent disk files.
select address -> signal read/write -> transfer data between registers and RAM
RAM holds executing programs and their working data
larger capacity than registers / cache, but still finite
RAM, cache and registers lose contents without power
5
disks / flash storage: persistent storage with access to arbitrary blocks
larger capacity and lower cost per unit than RAM
slower I/O through controllers
program code and working data must be loaded into RAM for CPU use
files normally reside here
6
magnetic tape: archival storage with sequential access
data normally copied to disk before use
drive expensive; many inexpensive cartridges reduce total cost per unit
appropriate storage conditions permit long retention
reading old media still requires compatible working equipment
Summary
The CPU executes instructions using registers and RAM. Buses connect
it to memory and device controllers; the OS manages resources and
drivers translate device operations.
Detailed notes - 1.1.6: Summary
1
CPU and RAM communicate through bus; external devices through controllers
drivers operate controllers
persistent files hold programs / data
load programs / data into RAM before processing
2
OS starts first and controls the machine
ordinary programs receive restricted access
operations beyond transforming assigned memory require OS services
3
these principles are prerequisites for programming
reread unclear material and resolve misunderstandings before proceeding
Using a Computer Properly
Unix treats the command line as a primary interface:
commands are fast, composable, repeatable, and easy to automate.
Operating Systems,
Interfaces, and Unix
The operating system starts and stops programs and
provides uniform access to files, devices, memory, and other
resources.
A user interface is not necessarily part of the OS.
Unix can use a shell, a graphical desktop, or both.
A command line is especially useful because commands can be combined
into pipelines and saved as scripts.
Period
Development
Late 1960s
MULTICS influences Ken Thompson's early Unix work at Bell Labs
1970s
Thompson and Dennis Ritchie develop Unix and the C language
1973
Most of Unix is rewritten in C, making portability practical
1977 onward
Berkeley develops BSD and major Unix networking tools
1984
Richard Stallman starts the GNU free-software project
1991
Linus Torvalds publishes the first Linux kernel
Today
Linux, BSD, macOS, Android, and commercial systems preserve Unix
ideas
For daily work:
use an unprivileged account; obtain administrator
rights only when required
keep a terminal one shortcut away
install a plain-text editor, compiler, assembler, build tool, and
debugger
prefer simple filenames made from Latin letters, digits,
., _, and -
never share your password or let another person use your
account
Detailed notes - 1.2.1: Operating systems and user interfaces
1
OS manages programs and peripheral devices
application requests a file by name and reads data into memory
OS handles device-specific work, including local / removable / network storage
2
book surveys Windows and the Unix family
Linux distributions, BSD systems, Android and Apple systems
describes relationships in the computing landscape of its edition
3
user interface can be an ordinary program outside the kernel
Unix separates interface programs from core OS responsibilities
book contrasts this with tighter Windows integration
4
many servers do not need a local graphical interface
machines run in equipment rooms; administrators manage them remotely
some have no video hardware at all
5
computer use does not inherently require graphics
text-mode file managers and even text-mode windows existed before widespread GUIs
6
widget interfaces arrange buttons, menus, input fields and other controls
command-line interface:
user enters commands; computer executes them and reports results
interactive dialogue differs from submitting batches of jobs
7
teleprinter: keyboard input travels through a communication line
received characters are printed on paper
originally used for remote written communication
8
connecting teleprinters to computers enabled interactive command entry
commercially available devices avoided designing a new terminal
9
alphanumeric screen terminals replace printed output with display output
keyboard still sends characters through a line
removes continual paper consumption
10
escape sequences control terminal display
move cursor, change attributes / colours, alter existing screen contents
11
terminal emulation reproduces terminal behaviour in software
serial connection can configure a server before network access exists
later administration normally uses the network
12
command interpreter / shell:
displays prompt, reads a command line, executes it
first word identifies command; following words are arguments
built-in commands handled by shell; others found as executable files
one line can combine several cooperating commands
13
Unix does not force users to avoid a GUI
book uses macOS as an example of Unix foundations with a graphical environment
professionals can also choose its terminal / shell
14
window manager controls window appearance and behaviour
Unix users can choose different managers independently of applications
15
Unix offers icon-based and two-panel file managers
author prefers shell commands for frequent file operations
16
book contrasts Unix shells with the Windows command interpreter of its period
notes availability of Unix-derived tools on Windows
17
both graphical and command interfaces require learning
familiar GUI gestures can conceal how much was learned
author argues that habit with one interface is not universal intuitiveness
18
command editing, history and filename completion reduce typing
photo-copy example:
enter destination year directory; create trip directory
mount card; copy photos; unmount card
Tab completes paths; history recalls commands / previous arguments
19
repeated command sequence can become a shell script
trip directory supplied as argument: ./getphotos Milan
improved version checks missing argument and reuses a destination variable
-> explicit commands allow the procedure to be parameterized and repeated
20
graphical applications can also start from a shell
program name followed by document / URL and other arguments
trailing & permits continued shell use
21
shell composition:
insert command output into another command
pipe one program's output into another program's input
combine existing tools in ways their authors did not anticipate
22
author treats command-line competence as essential professional preparation
also uses it as a teaching tool throughout the book
23
book assumes a Unix system and regular command-line work
remaining chapter introduces the required everyday skills
Detailed notes - 1.2.2: History of Unix
1
Bell Labs participation in MULTICS preceded Unix
after leaving the project, Ken Thompson developed a smaller system on a PDP-7
book relates the development to his interest in games and available hardware
2
UNICS name proposed by Kernighan; spelling later became Unix
Thompson and Ritchie moved system to PDP-11
B was too limited for desired system implementation
Ritchie's extension of B became C
3
Unix rewritten in C in 1973
challenged the assumption that an OS must be written in low-level language
linked the later development of Unix and C
4
1974 paper attracted users, especially at universities
AT&T's legal position encouraged noncommercial source distribution
port to Interdata 8/32 completed in 1977
portable C compiler helped separate system implementation from one CPU
5
Berkeley contributed the BSD branch
BSD = Berkeley Software Distribution
research began in the 1970s; Bill Joy produced first distribution in 1977
6
AT&T commercialization brought licensing disputes
Berkeley worked to remove AT&T-owned code
book describes eventual settlement after Unix business passed to Novell
7
legal uncertainty delayed freely available Unix on inexpensive Intel machines
80386 had suitable hardware capabilities before widespread free ports appeared
8
Stallman's free-software movement developed tools for a free system
lacked a complete free kernel
Torvalds began an independent Unix-like kernel for i386 in 1991
Linux name supplied by another participant; Torvalds had considered Freax
first public code in 1991; version 1.0 in 1994
BSD disputes helped Linux gain an early audience
kernel plus existing free tools provided a usable free system
12
Linux has many copyright holders
book explains distribution under GNU GPL v2
one company cannot simply purchase all contributors' rights as one owner's asset
13
Unix now denotes a broad family and shared approach
book distinguishes free Linux / BSD systems from commercial Unix variants
14
Unix foundations survived major changes in hardware and interfaces
graphical environments can be added without replacing core principles
Android uses Linux; Apple systems have BSD-related ancestry
Detailed notes - 1.2.3: Unix on a home computer
1
book introduces freely distributed Unix systems and their application packages
installation instructions and software available from their communities
2
author recommends a Linux distribution for the first installation
BSD variants can be explored after gaining experience
3
transition can be gradual; immediate abandonment of the previous environment unnecessary
4
separate spare computer is one possible installation target
lightweight systems can make older hardware useful
very old hardware may restrict available application versions
5
another option: allocate disk space alongside an existing OS
preserve needed files before repartitioning / replacing a filesystem
book's quoted capacity is an example from its period
6
author prefers a lightweight window manager
distinguishes window management from a complete desktop environment
this preference supports the book's emphasis on shell use
7
find and configure a terminal emulator
book suggests an 80-column layout and comfortably readable character size
background / text colour recommendations reflect the author's preference
8
make opening a terminal easy
keyboard shortcut or readily accessible launcher
save suitable font / window settings
-> comfortable setup reduces friction during study
9
install applications needed for ordinary work
browser, office documents, PDF / image viewing, audio / video
learn the equivalents of familiar tasks in the new environment
10
book's programming tools:
text editors: Vim, JOE, nano
Free Pascal, NASM, GCC with C / C++ support
make and GDB
package names can differ between systems
11
use an unprivileged account for ordinary work
administrative access reserved for system changes
book additionally expresses its own preference for separate root sessions over sudo
console-switch key examples depend on system configuration
Detailed notes - 1.2.4: First session in a computer classroom
1
classroom Unix may run locally or on a shared remote server
basic user workflow remains similar
2
log in with assigned username and password
letter case matters; Login incorrect can mean either value is wrong
3
obtain a shell
remote terminal / text console normally provides it after login
graphical session: open xterm or another terminal emulator
book uses startx for starting an X session where configured
4
change an initially assigned password using passwd
current password, then new password twice; characters are not echoed
book gives a mnemonic phrase method and period-specific composition advice
keep account credentials private; do not let others work under your identity
Files and Paths
Unix has one tree. / is its root, ~ is the
home directory, . is the current directory, and
.. is its parent.
Command
Purpose
pwd
Print the current directory
ls -aF
List all entries and mark their types
cd dir
Enter dir
cd
Return to the home directory
cp src dst
Copy a file
mv old new
Move or rename a file
rm file
Remove a file
mkdir dir
Create a directory
rmdir dir
Remove an empty directory
touch file
Create a file or update its timestamp
less file
View text page by page
/home/vasya/photos/mars.jpg absolute path
photos/mars.jpg relative path
../vasya/photos/mars.jpg relative path through the parent
./program program in the current directory
Each process has its own current directory. Changing
directory in one terminal does not change another terminal.
Detailed notes - 1.2.5: Directory tree and file operations
1
example prompt: user@host:directory$
prompt is printed by shell; do not type it as part of command
~ represents home directory; # conventionally marks administrator prompt
2
Unix path conventions:
one directory tree; no drive letters
/ separates directory components
3
login starts in home directory
pwd: print current directory
ls: list names; ls -a includes names beginning with .
ls -F marks types, including / for directories
. = current directory; .. = parent directory
4
cd changes current directory
cd tmp: child directory; cd ..: parent
cd /usr/include: specified absolute path; cd /: root
cd without argument: home directory
5
each process has its own current directory
changing directory in one shell does not change another shell's directory
6
basic file operations:
cp: copy; mv: move / rename; rm: remove
mkdir / rmdir: create / remove directory
touch: create empty file or update timestamps; less: view contents
options modify commands; rm -r removes a directory tree recursively
7
absolute path starts with / and is independent of current directory
/home/vasya/photos/mars.jpg identifies each component from root
8
short name refers to an entry in current directory
mars.jpg works when current directory is /home/vasya/photos
9
relative path starts from current directory
photos/mars.jpg from /home/vasya
../vasya/photos/mars.jpg from /home/anya
each .. ascends one directory level
10
paths can include redundant descents / ascents
system resolves these components rather than requiring a shortest spelling
useful when a program constructs a path from separate pieces
11
. can appear inside a path
./photos/./mars.jpg refers through the current directory at each . component
12
file path = name including directory components
commands generally accept absolute / relative paths wherever a filename is expected
13
book recommends simple portable filenames
letters, digits, . and _; - acceptable except as initial character
spaces / punctuation require quoting; leading - can be mistaken for an option
A command line contains a command name followed by arguments.
Semicolons separate commands.
ls -a ; pwd ; echo abrakadabra
mv Photos\ from\ Paris Photos_from_Paris
mv 'Photos from Paris' Photos_from_Paris
mv "Photos from Paris" Photos_from_Paris
Form
Meaning
\x
Treat the next character literally
'text'
Treat every character as literal text
"text"
Preserve spaces, but still allow selected substitutions
*
Any sequence of filename characters
?
Exactly one filename character
[abc]
One character from the set
[!abc]
One character outside the set
*.{jpg,png,gif}
Any listed suffix
The shell expands patterns before starting the
command:
rm *~
ls /etc/*.conf
cp files/* /mnt/flash
Detailed notes - 1.2.6: Commands and arguments
1
; separates commands executed one after another
separator belongs to shell syntax, not to either command's arguments
2
first word = command name; remaining words = arguments
shell supplies strings; command decides their meaning
echo prints its arguments
3
unquoted spaces separate words; extra separator spaces do not become argument data
interactive Tab normally requests completion
filenames containing spaces require a way to preserve those spaces
4
three ways to protect special characters:
backslash before character
single quotes around text
double quotes around text
quoting / escape syntax removed before arguments reach the program
protected ; is literal data rather than a command separator
5
single quotes preserve every enclosed character literally
a single quote cannot be escaped inside that quoted region
use another quoting / escaping context to include it
double quotes retain some special processing
variable / command substitution and selected backslash escapes still work
interactive history behaviour depends on shell
6
quoted and unquoted adjacent fragments form one word
shell expands unquoted filename patterns before running command
? matches one character; * matches any string, including empty
??? = three-character name; ???* = at least three characters
*.txt = names ending in .txt
one pattern can become many separate arguments
2
command receives expanded names, not instructions to expand a pattern
echo * prints names even though echo itself does not operate on files
patterns also work in paths, such as /etc/*.conf
3
[...] matches one member of a character set
img_27[234]?.jpg selects specified third digits
[!_]*.c excludes names beginning with _
4
brace alternatives generate several candidate patterns in shells supporting them
*.{jpg,png,gif} supplies patterns for three suffixes
5
unmatched patterns depend on shell behaviour
Bourne-style behaviour described here leaves the word unchanged
do not assume all shells / settings do the same
Efficient Shell Use
Key / command
Action
Tab
Complete a name; press twice to list alternatives
Up, Down
Move through command history
Ctrl-R
Search history backward
history | less
Browse saved commands
!!
Repeat the previous command
!137
Repeat history entry 137
Ctrl-C
Cancel the current input or interrupt a program
Do not retype what the shell already knows.
Detailed notes - 1.2.8: Command history and filename completion
1
modern shells avoid repeatedly typing entire commands
2
Tab completes a uniquely determined name
ambiguous prefix: request possible completions, then type enough to distinguish
some shells complete command-specific arguments too
3
history stores previous commands, often across sessions
Up / Down select earlier / later commands
ordinary cursor / editing keys modify recalled text
4
history | less displays numbered history
!137: command 137; !!: previous command
!:0: previous command word; !:1: its first argument
!137:2: word 2 from command 137, numbering from zero
!abc: latest command beginning with abc
5
Ctrl-R searches history backward by substring
type search text; repeat Ctrl-R for earlier matches
6
Ctrl-C cancels a confused / unwanted input line
7
practice completion and history as ordinary working habits
author stresses their cumulative saving of typing time
Processes and Jobs
Key / command
Meaning
Ctrl-D
Send end-of-file; at a shell prompt, exit cleanly
Ctrl-C
Send SIGINT to the foreground process
Ctrl-\
Send SIGQUIT
Ctrl-S, Ctrl-Q
Pause and resume terminal output
Ctrl-Z
Suspend, not terminate, the foreground process
ps ax
List processes
top
Show active processes interactively
kill PID
Send SIGTERM
kill -9 PID
Force termination with SIGKILL
Background and foreground jobs:
updatedb & # start in the background
jobs # list shell jobs
kill %2 # signal job 2
bg # continue a suspended job in the background
fg # bring a job to the foreground
Closing a terminal window is not a reliable way to terminate its
processes.
A programming editor must save plain text, avoid
automatic paragraph formatting, and use a monospaced
font. Common terminal choices include Vim, nano, JOE, and the
Midnight Commander editor.
Permissions are grouped as owner, group,
and others:
Bit
Value
File
Directory
r
4
Read contents
List names
w
2
Modify contents
Create, rename, or remove entries
x
1
Execute
Enter and access entries
ls -l /bin/cat # -rwxr-xr-x, or 0755
chmod 644 myfile.c # owner: read/write; others: read
chmod a+x myscript # make a script executable
chmod go-rwx private # remove all group/other access
Use the local manual before guessing:
man ls
man 2 write # section 2: system calls
man 3 sprintf # section 3: C library functions
Inside man: /text searches,
Space advances a page, and q exits.
Detailed notes - 1.2.12: Text editors
1
Unix offers many editors; section introduces several terminal editors
2
programming editor requirements in the book:
plain text files; no automatic paragraph reformatting
monospaced display keeps code columns aligned
equal runs of m and i should occupy equal width
3
Vim = improved clone of vi
modal interface initially unfamiliar
efficient text operations become useful after practice
4
emergency Vim exit without saving: Escape, then :qa! and Enter
5
vim filename opens file; missing file created when first saved
begins in command mode
insert mode accepts text; command mode interprets keystrokes as operations
6
command-mode cursor movement: h left, j down, k up, l right
arrow keys usually available too
7
arrow keys transmit multibyte escape sequences
slow connections can make these ambiguous with pressing Escape followed by commands
8
enter insert mode with i / a, or o / O for a new line below / above
Escape returns to command mode
^ / $ move to line start / end; x, dw, dd, d$ delete different units
J joins lines; . repeats change; u undoes; U restores line changes
9
/text followed by Enter searches forward
/ followed by Enter repeats previous search
10
:number followed by Enter jumps to a line
file commands:
:w save; :w name save under another name
:wq save and exit; :q exit if unchanged; :q! discard changes and exit
:r name insert file; :e name edit another file
:ls list buffers; :b N select buffer N
11
Ctrl-^ switches between recent buffers
:set hidden permits leaving a modified buffer without saving
~/.vimrc stores startup settings
12
V selects whole lines; v selects characters
movement extends selected region
13
d cuts selection; y copies it; p / P pastes after / before cursor
deletion commands also place removed text in a register
yy, yw, y$ copy line, word, or remainder of line
14
vimtutor provides guided practice
15
GNU nano: free reimplementation of Pico, originally related to Pine mail editing
nano filename; ordinary typing immediately inserts text
Detailed notes - 1.2.14: Online documentation: man
1
Unix distributions include local documentation; man displays manual pages
2
manual covers commands, system calls, library functions, file formats and concepts
man ls describes ls; man waitpid describes that interface
scroll with arrows / Space; q exits viewer
3
/ searches forward for text; repeat search without retyping text
? searches backward
4
manual section disambiguates names
man 2 write selects system call rather than user command
1 commands; 2 system calls; 3 library functions; 4 devices
5 file formats; 6 games; 7 general concepts; 8 administration
additional installed software can introduce other section names
Shell Scripts and
Environment
An executable shell script starts with a shebang
naming its interpreter:
#!/bin/sh
if [ "$1" = "" ]; then
echo "usage: $0 directory" >&2
exit 1
fi
mkdir "$1"
echo "created: $1"
chmod +x make-dir.sh
./make-dir.sh Paris
./ is required because command names without
/ are searched for only in directories listed by
PATH.
Variable
Meaning
$0
Script name
$1, $2, ...
Positional arguments
$#
Number of arguments
PATH
Directories searched for commands
HOME
Home directory
LANG
Language and locale
EDITOR
Preferred text editor
env # show the environment
export PATH="$PATH:/sbin" # change inherited configuration
unset MYVAR # remove a variable
EDITOR=joe chfn # change one command's environment
Child processes inherit the environment of their parent.
The special parameters in a small script:
#!/bin/sh
echo "My name is " $0
echo "I've got " $# " parameters"
echo "Here are the first three of them, in reverse order:"
echo "" "$3 $2 $1"
$ sh argdemo.sh one two three
My name is argdemo.sh
I've got 3 parameters
Here are the first three of them, in reverse order:
three two one
Arithmetic uses $(( )); braces separate a variable name
from the text after it:
I=10
I=$((I+7))
echo ${I}abs # 17abs; $Iabs would be another, empty variable
Etude 1.10 prints M consecutive numbers starting from N, and rejects
a missing argument with a message on stderr and a nonzero status:
#!/bin/sh
if [ $# -lt 2 ]; then
printf "Error: Enter 2 parameters\n" >&2
exit 1
fi
N=$1
M=$2
L=$(( N + M))
while [ "$N" -lt "$L" ]; do
echo -n "$N" ""
N=$(( N + 1))
done
echo
#!/bin/sh
echo "Humpty Dumpty sat on a wall,"
echo "Humpty Dumpty had a great fall."
echo "All the king's horses and all the king's men"
echo "Couldn't put Humpty together again."
unlike startx from an existing shell, login must establish session environment
sourcing ~/.profile and ~/.xinitrc can share configuration
12
window managers differ from full desktop environments
desktop environments add desktop metaphor and supporting services
book lists both categories as choices
13
a desktop environment may contain a separate window-manager program
its components need not work independently
14
book traces desktop metaphor to Xerox PARC research and Xerox Alto
15
book's historical survey follows later adoption in personal computers
graphical usability depended partly on improving hardware speed
16
many distributions provide a desktop environment by default
book links this to familiar interfaces for migrating users
17
author objects to desktop environments consuming resources needed by applications
18
desktop environments may create conventional user directories automatically
desktop directory contents can appear as icons
localized / spaced names require appropriate handling in shell commands
19
author recommends trying lightweight managers to support command-line study
IceWM offered as initial example; experimentation encouraged
20
graphical login may expose a session-type selector
otherwise configure appropriate startup file
example starts xterm in background and IceWM in foreground
21
book calls twm / fvwm-style managers classical
contrasts their behaviour with click-to-focus / raise interfaces
22
focus can follow pointer without raising window
type into a partly obscured window without rearranging all windows
23
behaviour is configurable; exact gestures depend on chosen configuration
24
find root-window menu and start a terminal
xterm & starts another terminal while preserving current shell availability
25
xterm options configure appearance
-bg black -fg gray is the book's colour example
26
title / frame gestures raise, lower, move and resize windows
corners commonly resize; title commonly moves
27
window-list menu helps locate hidden windows
28
virtual screens organize larger sets of windows
some managers treat them as adjacent regions of one larger desktop
a window may extend beyond one physical-screen region
29
X selection provides text transfer between applications
select text; middle-click pastes selection
clipboard copy / paste may be a separate parallel mechanism
mouse wheel press often acts as middle button; Shift-Insert may paste
X Window keeps graphical responsibilities separate:
application (X client) -> X server -> display and input devices
window manager -> borders, titles, placement, virtual desktops
A Little Bit of Mathematics
Programming relies heavily on discrete mathematics:
finite choices, numeral systems, logic, and computability. The important
habit is not memorizing formulas, but seeing what is being counted or
transformed.
Detailed notes - 1.3: Some mathematics
1
discrete mathematics supplies prerequisites for later programming material
chapter develops the needed reasoning rather than assuming school coverage
Combinatorics
Combinatorics counts possibilities. The safest method is:
split the situation into choices
multiply independent choices
divide when the same result has been counted several times
If each of
independent positions has
possible values, then there are
different strings. For example,
independent yes/no choices give
possibilities. This is also why a set of
elements has
subsets: for each element we choose either "take it" or "do not take
it".
For permutations, the number of choices decreases by one after every
pick:
There is one empty ordering, so
.
That convention makes formulas work at the boundary.
Ordered selection of
distinct items from
items:
The first form shows the reason: choose the first item in
ways, the second in
ways, and so on.
Unordered selection removes the order after counting ordered
selections:
Each unordered group of
items was counted once for every internal ordering of those
items, namely
times.
Edges in a complete graph of
vertices:
From each vertex we can go to
other vertices, so
counts directed endpoints. An undirected edge is seen twice, once from
each end, so we divide by
.
Useful binomial identities:
Why they hold:
and
count the single choice "take nothing" or "take all".
because choosing the taken
items is equivalent to choosing the excluded
items.
splits by one distinguished item: either it is excluded
()
or included
().
counts all subsets by their size, so the result is
.
The recurrence builds Pascal's triangle. Row
contains the coefficients of the binomial expansion:
The coefficient
appears because, when multiplying
by itself
times, the term
is formed by choosing the
factors from which the
is taken.
Detailed notes - 1.3.1: Elements of combinatorics
1
combinatorics counts possible choices / arrangements of finite sets lamp example: fixed lamps independently on or off
one lamp gives two distinguishable signals
three lamps will give eight; explanation matters more than memorized answer
2
second lamp doubles possibilities
first lamp's two states with second off
same two states with second on -> four distinct combinations
3
each additional independent two-state lamp doubles count again
three lamps: 8; four: 16
N existing signals -> 2N after adding one lamp
4
zero-lamp case clarifies what is being counted
a signal groups many real situations rather than describing every detail
5
no lamps gives one distinguishable configuration
all situations look the same; there are not zero possible configurations
6
n lamps -> 2^n configurations, including 2^0 = 1
7
choosing which of five ornaments to wear is the same problem
unordered selection: put three of seven balls into a bag
permutations of the same three balls now represent one outcome
each triple appears six times among 210 ordered choices
22
every three-element choice has 3! orderings
-> 210 / 6 = 35 unordered choices
23
general combination count: C(n,k) = n!/[k!(n-k)!]
first count ordered selections, then divide by k! duplicate orderings
book warns against applying the formula without checking what is counted
24
reconstruct formula from reasoning when needed
discard unused positions from n! through division by (n-k)!
discard order of selected elements through division by k!
25
alternative derivation: arrange all n objects, then split into two bags
order within first bag irrelevant -> divide by k!
order within second bag irrelevant -> divide by (n-k)!
26
symmetry: C(n,k) = C(n,n-k)
selecting objects to take is equivalent to selecting objects to leave
27
boundary cases: C(n,0) = C(n,n) = 1
exactly one empty choice and one choice containing everything
28
combination counts are binomial coefficients
(a+b)^n = sum of C(n,k) a^(n-k) b^k
connection comes from counting contributions to each term
29
question is which coefficient multiplies each power combination
30
distributive law multiplies every term of one sum by every term of another
n terms times m terms -> nm products before collecting like terms
31
expanding n factors (a+b) gives 2^n uncollected terms
choose a or b from each factor independently
32
term a^k b^(n-k) appears once for each choice of k factors supplying a
-> coefficient C(n,k)
a^2 b^2 appears six times in expansion of (a+b)^4
33
Pascal's triangle computes coefficients using addition
first / last entry in each row = 1
inner entry = sum of two entries above
C(n+1,k) = C(n,k-1) + C(n,k)
combinatorial reason:
choices including new object select k-1 old objects
choices excluding it select k old objects
34
sum of row n is 2^n
classifies all subsets by their sizes
35
round-robin tournament with seven players
each plays six others, but each game counted for both players
-> 7 × 6 / 2 = 21 games
36
score-sheet explanation:
seven players prepare six sheets each -> 42 sheets
two sheets submitted per game -> 21 games
37
tournament grid has one row and one column per player
diagonal unused; each game recorded in two opposite cells
38
49 total cells minus seven diagonal cells = 42
two entries per game -> 21 games
39
complete graph: every pair of distinct vertices joined by one edge
n vertices, n-1 incident edges per vertex
n(n-1) edge ends; two ends per edge
-> n(n-1)/2 edges
Positional Numeral Systems
In base
,
each digit is in
and each position has weight
.
The rightmost digit counts units. Moving one place left multiplies
the weight by
,
because one digit in that position changes the lower range by a whole
block of
possibilities.
digit positions represent exactly
values:
through
.
This is the same multiplication rule as in combinatorics: each of the
positions has
choices.
The notation changes with the base; the number itself does not.
Binary groups cleanly into octal and hexadecimal because their bases
are powers of two:
Convert from base
by evaluating the digits:
The nested form is the same formula rearranged for computation: read
digits left to right, multiply the accumulated value by the base, then
add the next digit.
Convert an integer to base
by repeated division; the remainders, read in reverse order, are the
digits. The reason is the division identity:
The remainder
is the last digit, because every higher position is a multiple of
.
Then repeat the same reasoning for the quotient
.
For a fractional part, repeatedly multiply by
;
each resulting integer part is the next digit:
Multiplication by the base shifts the next digit into the integer
part.
A reduced fraction
terminates in base
exactly when
for some integer
.
Otherwise its representation is periodic.
Binary addition uses
;
multiplying by
shifts left by
positions.
The termination rule comes from the denominator. After
fractional digits, a terminating
base-
fraction has the form
So a reduced denominator must divide
.
If it never does, the long division process eventually repeats a
remainder, and the digit sequence becomes periodic.
A converter between decimal and hexadecimal, written in Pascal
(chapter 2). bas2num evaluates the positional formula digit
by digit:
function bas2num(h: string; b: integer): int64;
var
i, n: integer;
begin
bas2num := 0;
n := length(h);
for i := n downto 1 do
bas2num := bas2num + cha2int(h[i]) * pow(b, n - i);
end;
./hex ff h converts back and prints
ffh -> 255.
Show the complete program
program hex;
function pow(b, e: integer): int64;
var
i: integer;
begin
pow := 1;
for i := 1 to e do
pow := pow * b
end;
function cha2int(c: char): integer;
begin
if ord(c) >= ord('a') then
cha2int := ord(c) - ord('a') + 10
else
cha2int := ord(c) - ord('0')
end;
function int2cha(i: integer): char;
begin
if i >= 10 then
int2cha := chr(i - 10 + ord('a'))
else
int2cha := chr(i + ord('0'))
end;
function str2int(s: string): int64;
var
i, n: integer;
begin
n := length(s);
str2int := cha2int(s[1]);
for i := 2 to n do
str2int := str2int*10 + cha2int(s[i])
end;
function bas2num(h: string; b: integer): int64;
var
i, n: integer;
begin
bas2num := 0;
n := length(h);
for i := n downto 1 do
bas2num := bas2num + cha2int(h[i]) * pow(b, n - i);
end;
function num2bas(n: int64; b: integer): string;
var
i, e: integer;
x: int64;
begin
e := 1;
x := 1;
while x > 0 do
begin
x := n div pow(b, e);
e := e + 1;
end;
e := e - 2;
num2bas := '';
for i := e downto 0 do
begin
x := n div pow(b, i);
n := n - x * pow(b, i);
num2bas := num2bas + int2cha(x);
end
end;
var
h: string;
n: int64;
begin
h := ParamStr(1);
if ParamStr(2) = 'h' then
begin
n := bas2num(h, 16);
writeln(h, 'h -> ', n)
end
else
begin
n := str2int(h);
writeln(h, ' -> ', num2bas(n, 16), 'h')
end
end.
255 -> ffh
Detailed notes - 1.3.2: Positional numeral systems
1
position determines a digit's weight
radix / base n uses n digits and successive weights differing by factor n
decimal is the familiar base-10 instance
2
k independent positions with n possible states give n^k combinations
3
k base-n digits represent integers 0 through n^k-1
unused higher positions may be regarded as zero
4
adding 1 to n^k-1 exhausts k positions
next position becomes 1; lower positions become 0
its weight must therefore equal n^k
5
decimal's familiarity is historical habit
book stresses the relative simplicity of binary arithmetic
6
ordinary positional systems can use any integer base at least 2
digits have values 0 through n-1
1000 in base n means n^3
changing representation does not change the number or its properties
7
two decimal properties generalize:
value = sum of digit × corresponding power of base
repeated division by base yields digits as remainders, least significant first
is false only for
,
because a promise "if
,
then
"
is broken only when
happens and
does not.
These identities follow from the truth table. For example,
because the second input never blocks the value of
,
while
because one false input is enough to make an AND false.
De Morgan's laws:
The first law says that "neither
nor
"
is the same as
"
is false and
is false". The second says that "not both" is the same as "at least one
is false".
Other operations can be reduced to
,
,
and
:
These formulas describe the rows where the result is true.
is true when either
does not happen or
does. XOR is true in exactly two cases:
or
.
A truth table completely defines a Boolean function. For
input variables:
The first formula is the usual count of
independent binary choices. The second follows because each of those
rows may independently receive output
or output
.
Any truth table can be converted to disjunctive normal
form: for each row whose result is
,
AND together the required variables or negations, then OR all such
terms.
Example term for the row
:
That term is true on exactly that row and false everywhere else.
Detailed notes - 1.3.3: Binary logic
1
conditions in programs evaluate to true or false
file exists, value is in range, sufficient memory remains, etc.
2
Boolean algebra is a small part of mathematical logic
3
Boolean values: 0 false, 1 true
NOT reverses value: NOT 0 = 1, NOT 1 = 0
unary operation has one operand
4
binary operations have two operands
OR true if at least one operand true, including both
AND true only if both operands true
5
usual notation: OR written ∨; AND written & or ∧
6
XOR true when operands differ
unlike OR, false when both operands true
7
implication x -> y is false only for x true and y false
false premise makes material implication true regardless of consequent
book illustrates why a true conclusion alone does not establish true premises
8
Boolean function maps combinations of Boolean inputs to Boolean output
choose one output bit per combination -> 2^(2^n) functions
three inputs: 256; four: 65536
11
basic identities follow from operation meanings
x AND 0 = 0; x AND 1 = x
x OR 0 = x; x OR 1 = 1
AND sometimes written by juxtaposition, like multiplication
12
both distributive laws hold
(x OR y) AND z = (x AND z) OR (y AND z)
(x AND y) OR z = (x OR z) AND (y OR z)
13
idempotence, complements and double negation
x AND x = x; x OR x = x
x AND NOT x = 0; x OR NOT x = 1
NOT NOT x = x
14
De Morgan's laws:
NOT (x OR y) = (NOT x) AND (NOT y)
NOT (x AND y) = (NOT x) OR (NOT y)
derive by asking when original expression is false
15
reduce unfamiliar Boolean operations to AND, OR and NOT
implication: NOT x OR y
XOR: (x AND NOT y) OR (NOT x AND y)
truth-table construction of disjunctive normal form:
take every row with output 1
AND all variables, negating those that are 0 in that row
OR resulting terms
each term recognizes exactly its own input combination
Kinds of Infinity
Set
Size
Natural numbers
Countably infinite
Integers
Countably infinite
Rational numbers
Countably infinite
All finite strings over a finite alphabet
()
Countably infinite
Infinite digit strings / real numbers
Uncountable; continuum
A set is countable when its elements can be assigned
natural-number indices. A proper subset may have the same cardinality as
the whole set:
pairs the natural numbers with the even natural numbers.
Integers are countable because they can be listed without
omission:
Finite strings over a finite alphabet are countable because they can
be listed by length:
Each fixed length contains finitely many strings, so the whole list
remains countable.
Cantor's diagonal argument shows that no list contains every infinite
digit string: construct a new string whose digit
differs from digit
of item
.
The new string differs from every listed item.
For computation, the key boundary is:
finite descriptions belong to the countable set
arbitrary infinite objects form larger, non-constructive sets
Detailed notes - 1.3.4: Kinds of infinity
1
section prepares for computability discussion
author distinguishes intuitive algorithm concept from particular formal models
2
countably infinite set: elements can be numbered by natural numbers
naturals, even naturals and all integers are countable
countable enumeration promises another element, not completion of infinity
14
set theory also studies cardinalities beyond the continuum
power set of reals supplies an example
author distinguishes mathematical objects from directly executable constructions
15
continuum hypothesis: no cardinality strictly between countable infinity and continuum
book discusses independence from the usual set-theoretic axioms
answer depends on adopted axiomatic framework
Algorithms and Computability
With information encoded as finite strings, a computation has the
form:
means all finite strings over alphabet
.
Program texts are themselves finite strings, so there are only countably
many possible programs. But there are uncountably many functions from
to
.
Therefore most functions are not computable: there are
not enough finite programs to describe them.
No single informal definition captures every reasonable constructive
method. Instead, computability is studied through precise formal
models:
Model
Representation
Partial recursive functions
Basic functions plus composition, recursion, and minimization
Turing machine
Tape, states, read/write head, and transition table
Markov algorithm
Ordered string-rewriting rules
Lambda calculus
Function abstraction and application
Register machine
Instructions operating on unbounded registers
All established general models compute the same class of
functions.
Church's thesis: every effectively computable
numerical function is partial recursive.
Turing's thesis: every effective algorithm can be
implemented by a Turing machine.
These are theses, not theorems, because "effective procedure" is the
informal concept being modeled.
Different algorithms may compute the same function. For example, the
Towers of Hanoi can be solved by a recursive decomposition or by a
parity-based iterative procedure. The recursive count is:
To move
disks, move
disks aside, move the largest disk once, then move the
disks onto it. Solving the recurrence gives:
Detailed notes - 1.3.5: Algorithms and computability
1
information processing can be represented as a function on finite strings
choose finite alphabet A; input / result belong to A*
-> transformation A* -> A*
2
finite descriptions are countable; all string-to-string functions are uncountable
computation rules need finite descriptions
-> most mathematical functions have no such computable rule
3
even functions from naturals to decimal digits form an uncountable set
each function specifies an infinite sequence of digits
allowing arbitrary natural outputs does not remove the disparity
4
Boolean-valued functions on naturals correspond to subsets of naturals
true means membership; false means nonmembership
-> power set of naturals is uncountable
5
program embodies a constructive procedure / algorithm
programmer supplies rules precise enough for independent execution
a function is computable when such a rule computes it
6
author objects to school definitions treating a short verbal description as a complete account
emphasizes distinction between informal effective procedure and a fixed formal definition
7
computability theory grew from questions of algorithmic solvability
Hilbert's problems, especially the tenth problem, motivated formal investigation
Gödel, Kleene, Church and Turing contributed central models
8
book narrows its treatment to discrete representations
arbitrary real values cannot all be supplied as finite input descriptions
9
natural-number functions suffice for encoded countable domains
replace each finite object by its enumeration number
10
uncountably many natural-number functions still exceed countably many finite procedures
11
partial recursive functions:
start from simple functions: constants, successor and projections
build through composition, primitive recursion and minimization
partial functions may be undefined for some inputs
recursive here describes the formal construction, not only self-calling procedures
12
many proposed computation formalisms yield the same class
extra-looking operations can be simulated by existing ones
13
Church's thesis identifies effectively computable functions with partial recursive functions
a thesis connecting informal effectiveness to a formal class
not a theorem about two already formalized definitions
14
author emphasizes the distinction between evidence for a thesis and formal proof
hypothetical stronger effective model would challenge the thesis
15
book compares this thesis with an empirical hypothesis
author emphasizes usefulness of unrestricted while loops and recursion
their availability removes automatic termination guarantees
individual uses can still compute total or primitive-recursive functions
31
general effective-computation models therefore admit procedures undefined on some inputs
distinguish this theoretical possibility from correctness requirements of a particular program
Algorithms Are
Not Necessarily Action Sequences
An algorithm describes an effective computation, not necessarily an
explicit ordered list of commands.
Paradigm
Program describes
Imperative
State-changing actions, as in C or Pascal
Functional
Functions and expressions; evaluation may be lazy
Declarative / logic
Required properties and relations, as in Prolog
Object-oriented
Objects exchanging messages
Rewriting systems
Rules for transforming symbols or terms
Formal models and programming paradigms can express equivalent
computations without exposing the same action order. Every executable
programming language is algorithmic; imperative and
non-imperative is the useful distinction.
Detailed notes - 1.3.7: A sequence of actions is not the whole idea
1
algorithm need not be written as an explicit sequence of imperative actions
2
equivalent formal models have different representations
Prolog example: facts and rules used in a proof / search process
5
object-oriented viewpoint emphasizes objects and messages
imperative languages such as Pascal / C describe state-changing actions
dominant hardware architecture helps explain popularity of imperative style
6
programs in executable languages still express effective computations
non-imperative does not mean nonalgorithmic
author's comments about heuristics / neural networks are opinions in this discussion
7
recursion even in imperative languages can obscure a direct action sequence
therefore surface syntax is a poor test of algorithmic character
8
use imperative / non-imperative for the intended distinction
reserve algorithmic for computability rather than action-list notation
9
terminology disputes should not obscure substantive mathematical results
10
a universal tool correctly detecting every nonterminating program would solve halting problem
-> impossible under the model just discussed
11
undecidability limits general automatic reasoning about arbitrary programs
does not rule out proofs about particular programs or restricted classes
12
author notes that programmers may recognize diagonal halting proof without knowing formal computability vocabulary
13
bounded versus unrestricted computation connects theory with programming practice
partial recursive / Turing-computable class models general programs
primitive-recursive constructions provide a useful restricted total class
Programs and Data
Inside a computer, programs and data are stored as bit patterns. The
same bits can represent an integer, text, a floating-point number, an
instruction, or part of a file; the meaning comes from the convention
used to interpret them.
Measuring Information
A bit is the amount of information that cuts
uncertainty in half. If a problem initially has
equally possible variants and a message leaves
variants, then the information gained is
bits. A yes/no answer gives at most one bit because it has two
possible outcomes.
To guarantee finding one object among
equally possible objects with yes/no questions, the required number of
questions is
For example:
The strategy is binary search: split the remaining possibilities into
two nearly equal parts at every step.
If an event has probability
,
then learning that it happened gives
bits of information. Less probable events carry more information when
they are confirmed.
Examples:
bits are needed to distinguish one of three equally likely
alternatives.
bits are gained when a search area shrinks from
to
.
A byte normally means eight bits, also called an
octet when the eight-bit size must be explicit:
So one byte can store one of
different bit patterns.
Detailed notes - 1.4.1: Measuring information
1
bit = binary digit
computer represents information using combinations of zeros and ones
2
information reduces uncertainty
one bit corresponds to halving an equally likely set of possibilities
distinguishing one of 1000 numbers needs at most ten well-chosen yes/no questions
3
divide remaining possibilities into two equal or nearly equal groups
ask which group contains answer; discard other group
at most 1000 -> 500 -> 250 -> 125 -> ... -> 1
4
ordered interval makes the same procedure easier
ask whether number lies in lower or upper half
retain corresponding interval and repeat
5
information amount need not be an integer number of bits
card trick repeatedly asks which of three rows contains chosen card
6
27-card trick:
deal into three rows; place indicated row between other two
deal cyclically again; candidates now middle three cards of each row
repeat; third answer identifies middle card
gathering indicated row in middle puts chosen card fourteenth in deck
7
each three-way answer reduces candidates by factor 3
one trit = log2(3) bits
8
treasure-search example:
area shrinks from 60 × 80 to 30 × 20
eightfold reduction under uniform-location assumption -> log2(8) = 3 bits
9
probability example assumes independent matches
win probabilities 1/4 and 1/2 -> both wins probability 1/8
information in this outcome = -log2(1/8) = 3 bits
10
both losses probability 3/8
information = log2(8/3) = 3 - log2(3) bits
more probable event conveys less surprise
11
byte usually means eight bits; historical machine usage varied
octet unambiguously means exactly eight bits
12
eight bits give 256 patterns
can represent unsigned 0-255 or signed -128-127
one-byte character codes suffice for limited alphabets, not all writing systems
13
adjacent memory locations form a region for larger values
same storage also holds program instructions
14
memory does not record the intended interpretation of bytes
41 4E 4E 41 hexadecimal can be read as ANNA, integer, float or instructions
operation / program context determines interpretation
15
large information units have historically ambiguous decimal / binary usage
KB, MB, GB etc. require attention to convention
16
N binary address lines distinguish 2^N memory locations
17
installed memory can be smaller than address space
bank selection and location selection divide address bits
18
memory capacities naturally relate to powers of two
several banks need not themselves total one power of two
19
historical K meant 1024 locations / words, close to decimal thousand
8192-location bank = 8 K; three such banks = 24 K
20
smaller addressable bytes allowed multiple characters per machine word
byte-based capacity notation later became common
21
binary usage extended to 2^20, 2^30, 2^40 bytes
storage manufacturers also used decimal powers consistent with SI prefixes
22
difference between decimal and binary interpretations increases with exponent
small at kilo scale, substantially larger at tera scale
23
communication rates conventionally use decimal multiples of bits per second
link transmission does not inherently follow memory's binary capacities
24
binary prefixes remove ambiguity
Ki = 2^10, Mi = 2^20, Gi = 2^30, Ti = 2^40
B denotes byte; bit denotes bit
GiB means 2^30 bytes
25
book describes slow adoption and continued historical usage
especially when discussing RAM
26
unambiguous meaning is the advantage of KiB / MiB / GiB notation
Machine Representation of
Integers
Real machines allocate a fixed number of bits for an integer. With
bits, unsigned arithmetic has exactly
different bit patterns, interpreted as
If a result does not fit, the extra carry is lost and arithmetic
wraps around:
For
:
When an integer occupies several bytes, architectures choose a byte
order:
Order
Memory layout for
Big-endian
00 00 1D 4C
Little-endian
4C 1D 00 00
The value is the same; only the order of bytes in memory changes.
Signed integers are usually stored in two's
complement. The same
-bit
pattern has signed value
where
is the unsigned interpretation of the bit pattern.
Thus the representable signed range is
For eight bits:
To change the sign in two's complement, invert all bits and add
one:
Example for
in eight bits:
The reason this works is modular arithmetic:
The processor can therefore use the same addition circuitry for
subtraction. For unsigned arithmetic, the important event is carry out
of the fixed width. For signed arithmetic, the important event is
overflow, when a result crosses the boundary between
and
.
Detailed notes - 1.4.2: Machine representation of integers
1
mathematical integers have no largest value
any fixed physical representation has finite capacity
2
machine integer commonly allocated fixed width: 8,16,32 or 64 bits
decimal mechanical counter illustrates limited positions and carry
3
fixed-width counter eventually wraps
99999 + 1 -> 00000 in five decimal positions
carry goes beyond available positions
4
unsigned n-bit integer range: 0 through 2^n-1
eight bits: 0-255; 255+1 discards carry in fixed-width hardware result
general radix-N, k-digit maximum: N^k-1
5
arbitrary-precision arithmetic allocates more storage as needed
limited by resources; extra software work compared with fixed-width operations
6
multibyte values require a byte-order convention
little-endian: least significant byte at lowest address
program hex;
function pow(b, e: integer): int64;
var
i: integer;
begin
pow := 1;
for i := 1 to e do
pow := pow * b
end;
function cha2int(c: char): integer;
begin
if ord(c) >= ord('a') then
cha2int := ord(c) - ord('a') + 10
else
cha2int := ord(c) - ord('0')
end;
function int2cha(i: integer): char;
begin
if i >= 10 then
int2cha := chr(i - 10 + ord('a'))
else
int2cha := chr(i + ord('0'))
end;
function str2int(s: string): int64;
var
i, n: integer;
begin
n := length(s);
str2int := cha2int(s[1]);
for i := 2 to n do
str2int := str2int*10 + cha2int(s[i])
end;
function bas2num(h: string; b: integer): int64;
var
i, n: integer;
begin
bas2num := 0;
n := length(h);
for i := n downto 1 do
bas2num := bas2num + cha2int(h[i]) * pow(b, n - i);
end;
function num2bas(n: int64; b: integer): string;
var
i, e: integer;
x: int64;
begin
e := 1;
x := 1;
while x > 0 do
begin
x := n div pow(b, e);
e := e + 1;
end;
e := e - 2;
num2bas := '';
for i := e downto 0 do
begin
x := n div pow(b, i);
n := n - x * pow(b, i);
num2bas := num2bas + int2cha(x);
end
end;
var
h: string;
n: int64;
begin
h := ParamStr(1);
if ParamStr(2) = 'h' then
begin
n := bas2num(h, 16);
writeln(h, 'h -> ', n)
end
else
begin
n := str2int(h);
writeln(h, ' -> ', num2bas(n, 16), 'h')
end
end.
Floating-Point Numbers
Floating-point numbers store a sign, a mantissa, and an exponent. In
normalized binary form:
The sign bit
determines the sign,
stores the significant bits, and
is the power of two. IEEE-754 formats usually store the exponent with a
bias:
For a normalized value with
stored mantissa bits:
where
is the integer represented by the stored mantissa field.
Common IEEE-754 formats:
Format
Total bits
Exponent bits
Mantissa bits
Bias
Single precision
32
8
23
127
Double precision
64
11
52
1023
Floating-point operations are approximate because the mantissa has
finite length. Addition can require shifting one mantissa right to match
exponents, and the shifted-out bits are lost.
Do not treat floating-point arithmetic like exact integer
arithmetic:
has a finite decimal notation, but not a finite binary notation. Its
stored floating-point value must be rounded. For this reason, testing
two floating-point results for exact equality is often the wrong
test.
Detailed notes - 1.4.3: Floating-point numbers
1
normalized binary floating point: N = (-1)^s M·2^P
sign s, significand / mantissa M, exponent P
ordinary normalized nonzero values use 1 <= M < 2
book discusses common IEEE-754 binary formats
2
leading 1 of normalized significand need not be stored
addition / subtraction aligns exponents by shifting smaller significand
calculate result, then normalize by adjusting significand and exponent together
multiplication / division also require normalization
4
finite precision introduces rounding
shifts or conversion can discard significant bits
values such as 1/10 have infinite repeating binary representations
computations generally approximate real arithmetic
exact equality after rounded computation may not match mathematical expectation
5
integer calculations within representable range remain exact
do not generalize floating-point rounding to all computer arithmetic
Texts, Languages, and
Encodings
Text is convenient for people, but unrestricted natural language is
extremely hard for programs to analyze. A formal
language is a set of strings built according to explicit
rules:
where
is an alphabet and
is the set of all finite strings over that alphabet.
Formal languages range from very small data formats to programming
languages:
Language kind
Purpose
Data format
Describe data in a program-readable way
Markup language
Describe text structure or presentation, as in HTML
Programming language
Describe algorithms or computations
Some programming languages are algorithmically
complete: any algorithm can be expressed in them, assuming
unlimited memory and time.
Text is still stored as numbers. An encoding maps
characters to byte sequences. ASCII is a seven-bit character set:
codes, enough for English letters, digits, punctuation, control
characters, and basic technical symbols. The historical association "one
byte = one character" came from storing ASCII characters in eight-bit
bytes.
Unicode is not itself one encoding; it is a registry of characters
and their code points. Encodings based on Unicode include UTF-8, UTF-16,
and UTF-32.
UTF-8 keeps ASCII compatibility and uses variable-length byte
sequences:
First byte pattern
Total bytes
Payload bits
0xxxxxxx
1
7
110xxxxx
2
11
1110xxxx
3
16
11110xxx
4
21
Continuation bytes start with 10xxxxxx. UTF-8 has three
practical advantages:
ordinary ASCII text is also valid UTF-8
byte order does not matter
concatenating UTF-8 strings keeps valid UTF-8, except possibly for a
fragment cut in the middle of a multibyte character
The tradeoff is that the
-th
character cannot always be reached by jumping to byte
,
because characters have variable byte length.
Detailed notes - 1.4.4: Texts and languages
1
natural-language text can describe a very wide range of information
2
natural-language analysis distinguishes morphology, syntax and semantics
ambiguous word forms require context
book describes semantic understanding as particularly difficult
3
author argues that neural-network language behaviour differs from explicit semantic analysis
discussion expresses the book's interpretation of contemporary AI
4
author stresses difficulty of explaining / correcting unexpected learned-system behaviour
his assessment is a viewpoint, not a programming-language definition
5
formal constraints make automatic analysis more manageable
users express information according to specified rules
6
formal language: language governed by explicit construction rules
mathematical notation and musical notation predate computers
7
for syntactic analysis, language can be viewed as a set of accepted strings
this abstraction does not by itself describe meaning / semantics
8
language design balances expressive needs and analysis complexity
measurement file might allow only numbers and separators
programming languages need richer constructions
9
storing / transmitting / displaying natural-language text does not require understanding its subject
editors, email and typesetting illustrate this distinction
10
ELIZA illustrates conversation produced through pattern manipulation
uses structure and words of input to construct replies
apparent conversational ability does not by itself reveal underlying method
11
many programming languages have been created; active communities maintain only some
12
markup languages describe document structure / presentation
HTML is the book's example; distinguish markup from general programming
13
any text-input program implicitly determines a language of accepted inputs
this language may be simple and unnamed
14
classification as programming can have disputed boundaries
SQL queries illustrate dependence on what is meant by a program
15
Turing-complete language can express a simulator of a Turing machine
provides a precise notion of computational expressive power
some languages designed for other purposes, such as TeX, are also Turing-complete
Detailed notes - 1.4.5: Text as a data format; encodings
1
text content and its stored representation are different
editors may save the same content in different formats
2
plain text uses character encodings without a document application's private formatting structures
ASCII originated as a code for interchange / teleprinter use
includes letters, digits, punctuation and control codes
3
ASCII uses seven bits -> 128 codes
0-31 controls; 9 tab, 10 line feed, 13 carriage return
32 space; decimal digits occupy 48-57
digit code minus 48 gives its numerical value
4
uppercase A-Z: 65-90; lowercase a-z: 97-122
corresponding ASCII letter cases differ by bit value 32
5
printable ASCII ends at 126 (~); 127 is DEL / RUBOUT
all-one punched-tape pattern could erase an existing character by punching remaining holes
UTF-32 uses four-byte code units; storage overhead is author's main objection
13
multibyte code-unit formats require attention to byte order and boundaries
BOM may identify byte order
arbitrary byte slices / concatenations need not be valid encoded text
14
UTF-8 is byte-oriented and preserves ASCII codes 0-127
non-ASCII Unicode code points use multibyte sequences
current Unicode UTF-8 uses one to four bytes; book also mentions obsolete longer forms
15
UTF-8 prefixes identify sequence structure
110xxxxx: two-byte lead; 1110xxxx: three-byte lead; 11110xxx: four-byte lead
following bytes start 10xxxxxx
payload capacities: 11,16,21 bits respectively
16
UTF-8 has no integer-byte-order dependency
slicing must respect character boundaries
variable byte length prevents direct character indexing by byte offset
correct display also needs suitable font glyphs
17
UTF-16 uses one or two 16-bit code units per Unicode scalar value
combines variable length with byte-order concerns
book strongly prefers UTF-8 and discusses historical Windows use
18
author recommends ASCII for portable program text in this course
broader encodings require attention to decoding, tooling and display support
Binary and Text Data
Text data is represented in a form meant to be read
and edited by humans. Binary data usually stores values
in the same compact representation used inside memory.
For
four-byte integers, the binary size is fixed:
The text representation depends on the number of digits and
separators. For the sequence
,
written one number per line:
bytes. The final
counts newline characters.
Binary is compact and easy for programs to read after they know the
format. Text is larger and requires parsing, but it is portable,
inspectable, and works well with standard Unix tools.
Use hexdump -C file to inspect bytes directly. In a
dump:
the left column is the offset from the beginning of the file
the middle columns are byte values in hexadecimal
the right column is a best-effort character view
For little-endian four-byte integer data, bytes
e8 03 00 00
represent
after reversing the byte order to read the numeric value.
Detailed notes - 1.4.6: Binary and textual data
1
text representation is directly readable by humans
binary representation uses another agreed encoding, often close to in-memory values
text size depends on number of digits, so need not always exceed binary size
3
text file can be inspected with cat or edited with an ordinary text editor
4
printing binary bytes as characters produces meaningless output
embedded terminal control sequences may alter terminal behaviour
reset can restore terminal settings
5
hexdump -C shows offsets, hexadecimal byte values and printable-character view
offsets advance by 16 bytes per displayed row
unprintable bytes represented by dots in character view
6
decode example using agreed four-byte little-endian format
e8 03 00 00 -> 0x000003e8 -> 1000
03 87 01 00 -> 0x00018703 -> 100099
7
hexdump of text shows digit codes rather than binary integer values
31 30 30 30 0a = characters 1000 followed by newline
8
computation requires converting numeric text to the machine's numeric representation
keep track of which representation each value currently has
Machine Code,
Translators, and Assembly
A CPU executes machine code: numeric codes for
machine instructions stored in memory. The instruction pointer tells the
CPU where the next instruction is.
Human programmers rarely write raw machine codes. A translator
bridges the gap:
Tool
What it does
Compiler
Translates source text into another representation, often machine
code
Interpreter
Executes source text or an internal representation while it remains
in memory
Assembler
Translates assembly mnemonics into machine instructions
A compact distinction:
with compilation, the compiler is needed to build the program, but
not to run the resulting machine-code program
with interpretation, the interpreter is part of the running
system
The boundary is not always clean: interpreters may compile internal
bytecode, and compilers may leave support code for runtime services. The
practical question is whether the translator must remain present while
the user program runs.
Assembly language replaces numeric machine-code bytes with mnemonics.
For example, a processor instruction encoded as bytes can be written
as
add eax, ebx
The assembler translates the mnemonic form to the exact machine-code
bytes. Unlike a high-level compiler, an assembler has very little
freedom: assembly source is already a near-direct description of the
machine instructions.
Detailed notes - 1.4.7: Machine code, compilers and interpreters
1
computer consists of CPU, memory and peripheral devices
introductory model connects them through bus / controllers
2
memory locations have addresses and fixed-width stored patterns
eight-bit location has 256 possible states
3
registers provide fast, limited CPU-local storage
CPU transfers data between registers and RAM and performs operations
4
machine word describes natural processor data width
often spans several addressable bytes
book's Pentium example uses 32-bit words and eight-bit bytes
5
instruction pointer and fetch / decode / execute cycle control execution
6
machine code consists of CPU instruction encodings
01 D8 on the book's x86 example adds EBX to EAX
operand bits encode register choices and addressing form
7
manually constructing / decoding large streams of numeric instruction codes is impractical
8
high-level source expresses operations in a form convenient for humans
execution requires an implementation such as compiler or interpreter
9
compiler translates source to another representation
Comments