The Octave Route
November 15, 202646 min readbeginner
Installs GNU Octave on macOS, Linux and Windows, teaches the Octave that the book's twin scripts use, from indexing to saturating integers, and shows how to hand numbers between Octave and Python without losing a bit.
Every companion script of Error Correction Coding exists twice. Beside each Python script in the book's companion repository, ecc-book-lab, sits a twin written for GNU Octave in the repository's octave folder, and the two print the same lines. This chapter is for readers who would rather check the book's numbers in Octave, or who move between the two languages. It installs Octave on macOS, on Linux and on Windows, runs a twin, teaches the Octave the twins are written in beside the Python taught in Setting Up the Lab Bench, and shows how to pass numbers from one route to the other and back without losing a bit. Every value it reports from a run of Octave or Python is reproduced by chf3_ecc_octave_route.py and by its twin chf3_ecc_octave_route.m, and the repository's compare-routes.sh checks that every pair agrees.
The Python route needs Python 3.10 or newer and nothing beyond its standard library. The Octave route needs GNU Octave 7 or newer and no Octave package. Given the option --handoff, each of this chapter's two scripts also starts the other language as a separate program and checks what comes back, so that one run needs both installed. The hardware labs have no twin, because cocotb, the library that drives their simulations, is a Python library, and the section on moving between the routes shows how an Octave session runs them anyway.
Everything here was run on macOS on Apple silicon, with Octave 11.3.0 and with Python 3.14.10 and 3.15.2. The Linux and Windows steps follow each project's documentation and were not run on those systems. Each install step follows Octave's own documentation, paraphrased and cited, and the versions named were the current ones when read on 2026-11-14. Tools move faster than books, so where a step here and a project's own page disagree, the project's page wins.
Two terms carry over from Setting Up the Lab Bench. An exit status is the number a program hands back when it ends, 0 for success. An ulp, a unit in the last place, is the gap between a double and the next double after it.
01.Why a Second Route
The book's numbers are not typed in by hand. Each one is computed by a script that prints it beside the value the chapter states, and the script stops at the first pair that disagrees by more than half a unit in the last digit stated, the rule set out in the half-unit test. A reader who learned numerical computing in Octave, or whose course uses it, can run that check without learning Python first, and Figure 1 shows how the repository serves both readers.
A twin is a promise about output, not about code. It prints the same labels and the same values in the same order as its Python script, so the two can be compared line by line by a program rather than by eye. Inside, a twin is written the way Octave is written, with whole vectors where the Python loops, and with helper functions where the two languages disagree. Those disagreements are the main subject of this chapter, because each one is a place where a number ported by hand from one language to the other silently changes.
02.Installing GNU Octave
macOS
Homebrew, which Setting Up the Lab Bench installed, carries Octave, and both Octave's download page and its wiki name Homebrew as a way to install it on macOS [1] [2].
| brew install octave |
Linux
Every major distribution packages Octave, and Octave's wiki gives the command for each [3]. On Arch Linux, the distribution this book's Linux and Windows routes use, the first line below installs it. The second serves Debian and Ubuntu, and the third Fedora.
| sudo pacman -S octave | |
| sudo apt install octave | |
| sudo dnf install octave |
A distribution's package can trail the current release by years, and an old long-term release may ship an Octave older than 7, which lacks the JSON functions the hand-off uses. The wiki also lists a build on Flathub, the Flatpak application store, which follows Octave's releases.
| flatpak install flathub org.octave.Octave | |
| flatpak run org.octave.Octave |
A Flatpak Octave starts through flatpak run rather than as a program named octave. The Python script finds Octave through a variable described later in this chapter, and with Flatpak that variable has to name a small wrapper script that runs the command above, a setup this book did not test.
Windows
The book's route on Windows is WSL2 with ArchWSL, as installed in Project: A Channel Simulator. Inside WSL2 with ArchWSL, the Arch commands above apply unchanged, and the scripts run there as they do on Linux.
Octave also ships a native Windows build [1] [4]. For version 11.3.0 it is the installer octave-11.3.0-w64-installer.exe, about 540 MB, or a zip archive to unpack, which carries a post-install.bat to run once after unpacking. The wiki advises installing into a folder whose path holds only ASCII characters, and a command window starts Octave without its graphical window as octave-launch.exe --no-gui. The native build runs the twins' Octave, but this book tested neither it nor the hand-off between a native Octave and a Python on Windows.
Checking the Version
Whichever way Octave was installed, one command reports its version. The first line it prints, on the Mac this book was tested on, is the one below.
| octave --version |
| GNU Octave (aarch64-apple-darwin27.0.0) version 11.3.0 |
Any version from 7 up runs the twins. Octave reads a handful of options when it starts, and Table 1 lists the ones this chapter uses, each with the description octave --help prints for it [5].
Table 1. The Octave options this chapter uses, with the descriptions octave --help prints for them.
| Option | Short form | Description from octave --help |
|---|---|---|
--gui | -g | Start the graphical user interface. |
--no-gui | -G | Disable the graphical user interface. |
--no-window-system | -W | Disable window system, including graphics. |
--norc | -f | Don't read any initialization files. |
--quiet | -q | Don't print message at startup. |
--eval CODE | -e | Evaluate CODE. Exit when done unless --persist. |
For typing at Octave interactively in a terminal, octave --no-gui is the command to use. It prints the prompt octave:1>, whose number rises by one with each line entered, evaluates each statement typed after it when Return is pressed, and leaves when exit is typed. The twins run with the other three options, so that no window opens, no startup file of the reader's changes a result, and no banner joins the output being compared.
03.Running a Twin
A twin runs from the repository's root folder, the same place its Python script runs from. The command below runs the twin of this chapter's script.
| octave --no-window-system --norc --quiet octave/chf3_ecc_octave_route.m |
It prints 113 lines, the same 113 its Python script prints, of which these are the first four.
| Indexing and ranges | |
| first element of [5 6 7]: v[0] in Python, v(1) in Octave 5 5 | |
| last element: v[-1] in Python, v(end) in Octave 7 7 | |
| elements in the Octave range 0:6 7 7 |
Each line holds a label, the value computed and the value the chapter states, and the last line reads "All chapter f3 numbers reproduced." Every twin begins, after its comment lines, with the same two statements.
| 1; | |
| addpath (fullfile (fileparts (mfilename ('fullpath')), 'common')); |
The first line, 1;, is a statement that does nothing. It is there because Octave treats a file whose first statement is function as a function file, which defines one function rather than running statements [6]. A twin defines helper functions of its own and runs statements too, so it opens with something other than function, and comment lines do not count as a first statement.
The second line reads from the inside out. mfilename ('fullpath') returns the full path of the file being run, without its .m. fileparts splits off the folder part of that path, fullfile appends the folder name common with the separator the system uses, and addpath puts the result on the list of folders Octave searches for functions. The twin then finds its shared helpers whatever folder Octave was started from.
The common folder holds four helpers. half_unit computes the tolerance a check allows from the text of the stated value, so half_unit ('0.0280') is 0.00005. py_g writes a number the way Python's format(x, '.9g') does, which for every finite number is the text Octave's sprintf ('%.9g', x) gives, and differs only in how infinity and not-a-number are spelled. py_str writes a value the way Python's str() does, and since Octave has one number type where Python has two, the caller marks which is meant. An integer type prints as a Python integer, so int64 (5) prints 5, while a double prints as a Python float, so 5 prints 5.0.
The fourth helper, PyRandom, is Python's random-number generator rewritten in Octave. Python's random module draws from the Mersenne Twister [7], and PyRandom carries out the same seeding, the same state updates and the same conversion of 32-bit words into doubles, holding each word in a double and splitting each product into 16-bit halves so that no step loses a bit. Octave's own rand turns out to match Python's draws too, as a later section measures, but Octave's documentation does not promise that, and rand has no counterpart of Python's getrandbits, choice or gauss, all of which the book's simulations use.
From Octave's own prompt, run executes a script in the current workspace [6]. A twin keeps its working values inside its own functions, so afterward who lists none of them, and what a twin leaves behind is the lines it printed.
| run ('octave/ch01_why_codes_exist.m') |
A twin that meets a mismatch calls exit (1), which closes Octave itself rather than only the script. From the shell, that exit status 1 is what the comparison tool reads. At the prompt, it means the session ends with the mismatch report as its last output.
04.Octave from First Principles
The twins use a small part of Octave, and this section teaches that part, each feature beside the Python it replaces. Every snippet is typed at the Octave prompt, and every output shown is what Octave 11.3.0 printed.
Everything Is a Matrix
Octave's basic value is a matrix of doubles. A single number is a matrix with one row and one column, and a list of numbers is a matrix with one row.
| v = [5 6 7] | |
| size (v) |
| v = | |
| 5 6 7 | |
| ans = | |
| 1 3 | |
Inside square brackets, spaces or commas separate the elements of a row and semicolons separate rows, so [1 2; 3 4] is a matrix with two rows. A statement without a semicolon at its end prints its value, and one with a semicolon prints nothing. A value that is not assigned to a name is stored in ans, which is why size (v) printed under that name. size reports rows first and columns second, so v is one row of three columns.
Every number typed is a double unless a function converts it. That is the first difference from Python, where 7 is an integer and 7.0 a float, two different types. Octave has integer types too, but a value becomes one only on request, and the section on integer types shows why the twins seldom ask.
Counting from One
Octave counts positions from one. The first element of v is v(1), and inside the parentheses of an index the word end stands for the last position.
| v(1) | |
| v(end) | |
| v(end-1) |
| ans = 5 | |
| ans = 7 | |
| ans = 6 |
Python counts from zero, so the same elements are v[0], v[-1] and v[-2]. Octave has no negative positions, and v(0) is an error.
| error: v(0): subscripts must be either integers 1 to (2^63)-1 or logicals |
Ranges differ in where they stop. The Octave range a:s:b starts at a, steps by s, and keeps every value that has not passed b, so 0:6 holds the seven integers from 0 to 6, end included. Python's range(7) holds the same seven, because it stops before its end. With a step of 2, 1:2:9 holds 1, 3, 5, 7 and 9, and so does 1:2:10, since the step after 9 would reach 11, past 10. Figure 2 sets the two conventions side by side.
Proof. The Octave range holds for every integer with , which is . Those are , a count of . Python's range holds for every with , where . Divide by as with . If , then exactly when , so the range holds elements. If , then while , so runs from 0 to and the range holds elements.
For 1:2:10 the theorem gives , and for range(1, 10, 2) it gives . To port range(a, b, s) with a positive step, the Octave range is a:s:(b-1).
Bit positions count from one as well. bitget (100, 1:7) returns the seven bits of 100 from the lowest up, which are 0 0 1 0 0 1 1, since . Bit 3 of that list, the one worth 4, is bitget (100, 3), which is 1, and its Python spelling is (100 >> 2) & 1, with the shift one less than Octave's position.
Doubles Are the Same Doubles
Python's floats and Octave's doubles are the same thing, the binary64 format of IEEE 754 [8]. Addition, subtraction, multiplication, division and the square root are rounded correctly by that standard, so those operations give the same bits in both languages, and 0.1 + 0.2 is the same double in each. What differs is how much of a double each language shows.
| x = 0.1 + 0.2 | |
| format long | |
| x | |
| format short | |
| printf ('%.17g\n', x) | |
| printf ('%.16g\n', x) | |
| x == 0.3 |
| x = 0.3000 | |
| x = 0.300000000000000 | |
| 0.30000000000000004 | |
| 0.3 | |
| ans = 0 |
Octave's display rounds to a few digits, and format long shows more but still not enough to tell x from 0.3. format short restores the usual display. Only printf with 17 significant digits shows that x is the next double above 0.3, which is what Python's repr prints, since repr gives the shortest text that reads back as the same double [9]. The comparison x == 0.3 gives 0, Octave's false. The hexadecimal of the bits settles it, since num2hex (0.3) is 3fd3333333333333 and num2hex (0.1 + 0.2) is 3fd3333333333334, one ulp apart.
Two constants describe the format. eps, the gap from 1 to the next double, is . flintmax is , the point below which every integer is a double. Past it, the doubles are 2 apart, so stored as a double becomes again.
Library functions are another matter. IEEE 754 recommends correctly rounded versions of functions such as exp and log but does not require them, the log-gamma function is not on its list at all [8], and each language calls its own code for these functions. The twins therefore never assume that Octave's version of such a function matches Python's to the last bit, and the section on checking the twins shows what one twin does instead.
Integer Types Saturate
Octave's integer types, int8 to int64 and uint8 to uint64, hold whole numbers in a fixed number of bits, and a result that does not fit saturates.
| a = uint8 (250) + 10 | |
| b = a - 10 | |
| c = uint8 (250) + (10 - 10) | |
| class (a) |
| a = 255 | |
| b = 245 | |
| c = 250 | |
| ans = uint8 |
A uint8 holds 0 to 255, so the true sum 260 becomes 255, the closest value that fits. C's uint8_t would instead wrap around modulo 256 and give 4, and a Python integer never overflows at all. Saturation also makes the order of operations matter, as Figure 3 shows, since (uint8 (250) + 10) - 10 is 245 while uint8 (250) + (10 - 10) is 250.
The same rule holds at both ends and for every width. uint8 (5) - 10 is 0, int8 (-100) - 100 is , the bottom of the int8 range, and int8 (127) + 1 stays 127. Converting a double into an integer type saturates and rounds, so uint8 (300) is 255, uint8 (2.5) is 3 and int8 (-2.5) is , each tie rounding away from zero.
Arithmetic that mixes an integer type with a double returns the integer type. For the types of 8, 16 and 32 bits the result is what the same arithmetic gives in double, rounded back into the integer type, so uint8 (1) + 1.5 is 3, since 2.5 rounds to 3, and its type is still uint8, while uint8 (200) * 2 is 255. The 64-bit types do not go through double, which would lose the bits above . int64 (2)^53 + 1 is 9007199254740993, where the same sum in double is 9007199254740992. Mixing two different integer types is an error [10].
| error: binary operator '+' not implemented for 'uint8 scalar' by 'int8 scalar' operations |
The safe course, and the one the twins take, is to keep numbers as doubles, which hold every integer up to exactly, and to convert with double () any integer-typed value a function returns before computing with it.
Division and Rounding
Dividing an integer type rounds the quotient to the nearest integer, ties away from zero. uint8 (7) / 2 is 4, since 3.5 rounds up, uint8 (5) / 2 is 3, and int32 (-7) / int32 (2) is . That matches neither of Python's integer divisions. Python's 7 // 2 is 3 and -7 // 2 is , because // rounds down, toward minus infinity [11], while int(-7 / 2) is , because int truncates toward zero.
In Octave the reliable spellings work on doubles. floor (-7 / 2) is , Python's -7 // 2, and fix (-7 / 2) is , Python's int(-7 / 2). The twins divide in doubles and take floor or fix of the quotient, which raises the question of whether a rounded double quotient can land on the wrong side of an integer.
Proof. Both and are exact doubles, and the division is rounded correctly, so the computed quotient is the double nearest and satisfies . If divides , then is an integer with , so is itself a double and . Otherwise, for every integer , the number is a nonzero integer, so . But , so no integer lies between and or equals , since such an integer would be closer to than . With no integer from one to the other, the two numbers share their floor and their ceiling. Because 0 is an integer, they also share their sign, and since truncation is the floor of a positive number and the ceiling of a negative one, they share their truncation as well.
Octave also has a function for integer division, idivide. Its help text says that the rounding option defaults to "fix", which truncates, and shows idivide (int8 ([-3, 3]), int8 (4), "fix") returning 0 0. Octave 11.3.0 does not do that.
Rounding to the nearest integer differs at ties. Octave's round sends a tie away from zero, so round ([2.5 -2.5 0.5]) gives 3, and 1. Python's round sends a tie to the even neighbor, so round(2.5) is 2 [12]. Octave's roundb follows Python's rule, and its help text reads "Return the integer nearest to X. If there are two nearest integers, return the even one (banker's rounding)." [13]
| round ([2.5 -2.5 0.5]) | |
| roundb ([2.5 -2.5 0.5]) |
| ans = | |
| 3 -3 1 | |
| ans = | |
| 2 -2 0 | |
roundb arrived in the Octave 3 series, so every version the twins support has it. The two directed roundings agree across the languages, fix (-3.5) being like Python's math.trunc(-3.5) and floor (-3.5) being like math.floor(-3.5) [14].
Two Remainders
Octave has two remainder functions, and its documentation defines each by the rounding it pairs with [13].
So mod takes the sign of the divisor, as Python's % does, and rem takes the sign of the dividend, as Python's math.fmod does. mod (-7, 3) is 2 and rem (-7, 3) is , while mod (7, -3) is and rem (7, -3) is 1. Figure 4 plots both for a run of dividends.
Proof. Subtracting the two definitions gives . When is an integer, and floor both return it. When , rounding toward zero is rounding down, so they agree again. When and is not an integer, rounding toward zero lands one above rounding down, so and the difference is .
The script checks both definitions over 574 pairs, from to 20 and from to 7 with , and finds and on all 574. The two remainders differ on 180 of them, which the theorem predicts. For each from 1 to 7, the dividends of the opposite sign that does not divide number , which sums to , and the two signs of double it to 180.
A zero divisor is where the languages part completely. Octave 11.3.0 gives mod (5, 0) as 5 and rem (5, 0) as NaN, not-a-number, while Python raises an error for both, ZeroDivisionError for 5 % 0 and ValueError for math.fmod(5, 0). A ported loop that can meet a zero divisor needs an explicit test before the call.
Bits and Binary Text
The bit operations have functions in Octave where Python has operators [15]. bitxor (100, 29) is 121, Python's 100 ^ 29, while bitand (100, 29) is 4 and bitor (100, 29) is 125. bitshift (100, -2) shifts right and gives 25, Python's 100 >> 2, and bitshift (100, 3) shifts left and gives 800, Python's 100 << 3.
The operator symbols are the trap, because Octave gives them other meanings. In Octave ^ is the power, so 100^29 displays ans = 1.0000e+58, the double nearest , where Python's 100 ^ 29 is 121. Octave's | and & are logical or and logical and, so 100 | 29 and 100 & 29 both give 1, true, since both numbers are nonzero. A line of Python bit arithmetic pasted into Octave runs without complaint and gives the wrong answer.
Binary text works much as in Python. dec2bin (100) is the text 1100100, Python's format(100, 'b'), and dec2bin (100, 8) pads it to 01100100, Python's format(100, '08b'). bin2dec ('1100100') reads it back as 100, Python's int('1100100', 2). Python counts the ones in 100 as (100).bit_count(), which is 3, and the same count in Octave is sum (dec2bin (100) == '1'), which compares each character with '1' and adds up the matches.
Parity, whether a word holds an odd number of ones, is the first error-detecting code the book meets, and it follows a clean rule under xor, a fact the twins lean on.
Proof. Look at one bit position at a time. If both bits are 0, the position adds 0 to every term. If exactly one is 1, it adds 1 to , 1 to and 0 to . If both are 1, it adds 0 to , 2 to and 1 to , and . Summing over the positions gives the identity, and reducing it modulo 2 removes the even term .
For 100 and 29, the counts are and , and has one 1, so , which 1111001 confirms.
Vectors and Arithmetic Mod 2
Octave has two multiplications. .* multiplies element by element, so [1 2 3] .* [4 5 6] is 4 10 18. * is the matrix product, so a row times a column, [1 2 3] * [4; 5; 6], is the single number 32. Asking * for a row times a row is an error, since the shapes do not fit the matrix product.
| error: operator *: nonconformant arguments (op1 is 1x3, op2 is 1x3) |
NumPy uses the opposite symbols, * for element by element and @ for the matrix product [11], so a NumPy line ported by eye changes meaning. Codes are built from matrix products taken modulo 2, and Octave writes that directly.
| G = [1 0 1; 0 1 1]; | |
| m = [1 1]; | |
| m * G | |
| mod (m * G, 2) |
| ans = | |
| 1 1 2 | |
| ans = | |
| 1 1 0 | |
The product counts, for each column, how many rows of G the message [1 1] selects with a 1 there, and mod reduces each count to its parity. The result 1 1 0 is the codeword this tiny code assigns to the message, and later chapters build every linear code this way.
Spaces inside brackets carry meaning, which creates one more trap. [ 1 - 1 ] is one element, 0, because a minus sign with spaces on both sides is subtraction, while [ 1 -1 ] is two elements, because a minus sign attached to the number that follows is the sign of that number. numel counts the elements and returns 1 and 2. Writing vectors with commas, as [1, -1], avoids the question.
The parity of several words at once takes three lines, and the twins use exactly this pattern.
| bits = dec2bin ([100 29 121]) | |
| ones_per_word = sum (bits == '1', 2)' | |
| parity = mod (ones_per_word, 2) |
| bits = | |
| 1100100 | |
| 0011101 | |
| 1111001 | |
| ones_per_word = | |
| 3 4 5 | |
| parity = | |
| 1 0 1 | |
Given a vector, dec2bin returns one row of text per number, padded to a common width. bits == '1' turns each character into a 1 or a 0, sum (..., 2) adds along each row, and the final apostrophe turns the resulting column into a row. The parity bits 1 0 1 make each word's count of ones even when appended, the even-parity rule.
Random Numbers That Match
Python's random.Random(1) and Octave's rand after rand ('state', 1) produce the same draws. Both use the Mersenne Twister [7] [16], and both turn a small integer seed into its starting state the same way, which was measured rather than read in either manual.
| rand ('state', 1); | |
| printf ('%.17g\n', rand ()) |
| 0.13436424411240122 |
That is the first draw of random.Random(1).random() to the last digit, and the 100,000th draw of each, 0.6355707617477253, agrees as well. For a seed above , Python splits the seed into 32-bit words, lowest first, and rand ('state', ...) accepts such a list, so the seed , whose words are 1 and 2, gives 0.5845141492495678 as its first draw both as random.Random(2**33 + 1) and after rand ('state', [1 2]).
Because the match is measured rather than promised, and because rand has no counterpart of getrandbits, choice or gauss, the twins draw from PyRandom, the helper described earlier, which reproduces Python's generator by construction.
JSON
JSON, a plain-text format for numbers, lists and records, is the easiest common ground between the routes, and Octave reads and writes it with jsondecode and jsonencode from version 7 on [17] [18]. Three details decide whether data crosses intact. First, jsondecode ('[100,29,121]') returns a column of three rows, not a row, as size reports with 3 1. Second, Python's json.dumps puts a space after each comma unless given separators=(",", ":"), which writes the compact [100,29,121] that jsonencode also writes [19].
Third, jsondecode reads every number into a double, so an integer above loses its last bits, and arrives as . An integer that large has to travel as a JSON string, text that Octave keeps character for character, and a string carrying 9007199254740993 arrives as exactly that. JSON's true arrives as a logical 1.
05.A Phrasebook
Table 2 collects the pairs this chapter has met, each with the value both sides give, for the vector 5, 6, 7 where an expression uses it.
Table 2. Python expressions and their Octave equivalents, with the value each pair gives.
| Python | Octave | Value |
|---|---|---|
v[0] | v(1) | 5 |
v[-1] | v(end) | 7 |
len(v) | numel (v) | 3 |
range(7) | 0:6 | 0 to 6 |
range(1, 10, 2) | 1:2:9 | 1 3 5 7 9 |
7 // 2 | floor (7 / 2) | 3 |
-7 // 2 | floor (-7 / 2) | |
int(-7 / 2) | fix (-7 / 2) | |
-7 % 3 | mod (-7, 3) | 2 |
math.fmod(-7, 3) | rem (-7, 3) | |
round(2.5) | roundb (2.5) | 2 |
math.floor(-3.5) | floor (-3.5) | |
100 ^ 29 | bitxor (100, 29) | 121 |
100 & 29 | bitand (100, 29) | 4 |
100 | 29 | bitor (100, 29) | 125 |
100 >> 2 | bitshift (100, -2) | 25 |
100 << 3 | bitshift (100, 3) | 800 |
(100 >> 2) & 1 | bitget (100, 3) | 1 |
format(100, '08b') | dec2bin (100, 8) | 01100100 |
int('1100100', 2) | bin2dec ('1100100') | 100 |
(100).bit_count() | sum (dec2bin (100) == '1') | 3 |
a * b, NumPy arrays | [1 2 3] .* [4 5 6] | 4 10 18 |
a @ b, NumPy arrays | [1 2 3] * [4; 5; 6] | 32 |
random.Random(1).random() | rand ('state', 1); rand () | 0.13436424411240122 |
json.dumps([100, 29, 121], separators=(",", ":")) | jsonencode ([100 29 121]) | [100,29,121] |
0.1 + 0.2 == 0.3 | 0.1 + 0.2 == 0.3 | False, and 0 in Octave |
In the two NumPy rows, a and b hold 1, 2, 3 and 4, 5, 6.
06.Moving Between the Routes
A reader who works in both languages will sooner or later compute something in one and finish it in the other, and the numbers then have to cross through a file. Integers below cross any reasonable way. Doubles need care, and the question is how many decimal digits a double needs so that the text read back gives the same bits.
Proof. Zero is written as 0 and read back exactly, and for any other the sign travels separately, so take , and take normal, with , so that the doubles there are apart. Let . The decimal written with 17 significant digits has its last digit worth , so . The reader returns the double nearest , which is whenever is less than half the gap from to each neighbor. If , both gaps are , and the condition holds because gives , which is less than since . If , the gap below is half as large, , and now gives , again since . A subnormal lies below , so and , less than the subnormal spacing .
IEEE 754 states the same bound, 17 significant digits for binary64, as the number that guarantees a round trip [8]. Sixteen are not enough, since 0.1 + 0.2 written with 16 digits is 0.3, which reads back as a different double, and an exercise below works through it. Python's float reads correctly, and str2double read back all 100,000 doubles of the test below, so both readers meet the theorem's assumption in practice.
The --handoff option of this chapter's scripts puts the theorem to work, and Figure 5 summarizes what it found. The Python script draws 100,000 doubles, half from random() and half from uniform(-1e6, 1e6) of a generator seeded with 7, writes them three ways and has Octave read each. Written by json.dumps and read by jsondecode, 89,493 arrive exact and every one of the other 10,507 is one ulp off. Written with 17 significant digits and read by str2double, all 100,000 arrive exact. Written as the hexadecimal of their 64 bits and read by hex2num, every bit arrives by construction, and that copy is the reference the other two are compared with.
The JSON losses happen on the reading side, and the reason can be deduced without knowing how jsondecode works inside. json.dumps wrote each double as the text repr gives, which the Python script's hand-off confirms for all 100,000, and repr gives text that reads back as the same double. The text was therefore correct, and the 10,507 misses come from how jsondecode turns it into a double. In the other direction, every double Octave's jsonencode wrote came back exact through Python's json.loads, as did every double Octave's fprintf wrote with 17 significant digits.
The advice that follows is short. To send doubles from Python to Octave, write them as text with 17 significant digits, f"{x:.17g}" in Python, and read them with str2double, or write the hexadecimal of their bits with struct.pack(">d", x).hex() and read it with hex2num. JSON is safe for integers below in either direction and for ordinary doubles from Octave to Python, and four cases mark the edge of that second promise. jsonencode writes as 0, so the sign is lost. It writes NaN, Inf and -Inf all as null, which json.loads reads as None. A whole-valued double such as 5 is written as 5 and comes back as a Python int, equal in value but of the other type. And jsonencode (1e19) writes 9223372036854775807, which is , not , while jsonencode (-1e19) writes . That last case suggests, without proving, that jsonencode writes a whole-valued double through a signed 64-bit integer, which saturates, so a whole number of size or more should travel as 17-digit text, as should any array that may hold , NaN or an infinity.
The hand-off runs from either side. From Python, the command below prints the chapter's 113 lines and then this block.
| python3 python/chf3_ecc_octave_route.py --handoff |
| Handing work to GNU Octave | |
| Octave 11.3.0 at /opt/homebrew/bin/octave | |
| parity bits Octave computed for [100 29 121] 1 0 1 1 0 1 | |
| idivide default against truncation, wrong of 3146 pairs 1184 1184 | |
| of those wrong, how many have a nonnegative dividend 0 0 | |
| idivide 'floor' against Python's //, wrong of 3146 pairs 0 0 | |
| idivide 'fix' against truncation, wrong of 3146 pairs 1184 1184 | |
| fix(a ./ b) on doubles against truncation, wrong of 3146 pairs 0 0 | |
| idivide(int8([-3 3]), int8(4)), documented as 0 0 -1 0 -1 0 | |
| idivide(int8([-3 3]), int8(4), 'fix'), documented as 0 0 -1 0 -1 0 | |
| elements in [ 1 - 1 ], where - is subtraction 1 1 | |
| elements in [ 1 -1 ], where - is a sign 2 2 | |
| doubles Python json.dumps wrote as their repr text 100000 100000 | |
| doubles exact after Python json.dumps, Octave jsondecode 89493 89493 | |
| largest of those misses, in units in the last place 1 1 | |
| doubles exact after Python %.17g text, Octave str2double 100000 100000 | |
| doubles exact after Octave jsonencode, Python json.loads 100000 100000 | |
| doubles exact after Octave %.17g text, Python float 100000 100000 | |
| draws of rand after rand('state', 1) equal to random.Random(1) 100000 100000 | |
| JSON text Octave's jsonencode writes for 1e19 9223372036854775807 9223372036854775807 | |
| Hand-off checks pass. |
From Octave, the twin's --handoff hands the chapter's three words, the 100,000 draws of rand and the 3,146 quotients of idivide to Python, which checks them and answers in JSON. The block it prints follows without its second line, which names the Python version that answered and the command that started it, and so differs from one machine to another.
| octave --no-window-system --norc --quiet octave/chf3_ecc_octave_route.m --handoff |
| Handing work to Python | |
| parity bits Python computed for [100 29 121] 1 0 1 1 0 1 | |
| draws of rand after rand('state', 1) equal to random.Random(1) 100000 100000 | |
| idivide default against truncation, wrong of 3146 pairs 1184 1184 | |
| of those wrong, how many have a nonnegative dividend 0 0 | |
| idivide 'fix' against truncation, wrong of 3146 pairs 1184 1184 | |
| fix(a ./ b) on doubles against truncation, wrong of 3146 pairs 0 0 | |
| idivide(int8(-3), int8(4), 'fix'), documented as 0 -1 -1 | |
| Hand-off checks pass. |
Each side finds the other through an environment variable. The Python script runs the program OCTAVE names, octave by default, and the twin runs the one PYTHON names, python3 by default, so a virtual environment's Python is chosen as PYTHON=.venv/bin/python in front of the Octave command. If Octave cannot be found, the Python script says so and exits with status 1, and the twin exits with status 1 when Python cannot be run.
The two languages start a program differently, and the difference matters for paths with spaces. Python's subprocess.run takes the program and its arguments as a list and starts the program directly, with no shell in between [20], so no argument needs quoting.
| subprocess.run([octave, "--no-window-system", "--norc", "--quiet", "handoff.m"], | |
| cwd=d, capture_output=True, text=True) |
Octave's system hands one string to a shell, which its help text says is typically /bin/sh on Unix systems and cmd.exe on Windows [21]. The shell splits that string at spaces, so the twin wraps every path in double quotes. Reduced to two arguments, its call reads as follows.
| cmd = sprintf ('"%s" "%s" "%s"', python, script, data_file); | |
| [code, output] = system (cmd); |
code receives the exit status and output everything the program wrote to its standard output, while anything it writes to standard error goes straight to the terminal. The same call is how an Octave session runs a hardware lab, whose testbench is Python by necessity. With the lab bench installed as in Setting Up the Lab Bench, and Octave started in the repository's root, the line below runs the parity lab's simulation, which builds under tb/parity/sim_build/, and returns what the lab printed in out.
| [status, out] = system ('.venv/bin/python tb/parity/run_parity.py'); |
07.Checking the Twins
The comparison tool runs each Python script and its twin and compares what they print.
| bash tools/compare-routes.sh | |
| bash tools/compare-routes.sh chf3 |
Without arguments it checks every chapter that has a twin, and with arguments only the chapters named. For each chapter it prints one line, starting PASS with the script's name, the number of lines compared and each route's run time, or starting FAIL with each route's exit status, followed by up to 20 lines of the difference between the two outputs. For this chapter the line reads PASS chf3_ecc_octave_route (113 lines; ...), with the times in place of the dots. The tool exits with status 0 when every chapter passes, 1 when any differs, and 2 when Python or Octave is missing, and it reads the same PYTHON and OCTAVE variables as the scripts.
Before comparing, the tool drops trailing spaces and turns every run of spaces into one space. That forgiveness has one cause. Python pads a label to a width counted in characters, while Octave's printf counts bytes, so a label holding a letter outside ASCII, such as a Greek , which takes two bytes, receives fewer padding spaces from Octave. Nothing else is forgiven, so a value that differs in its last printed digit fails the comparison.
On the test Mac, all 15 pairs pass, under both Python 3.14.10 and Python 3.15.2. The repository holds 29 Python scripts, and the other 14, whose names end in _charts, draw the book's figures rather than reproduce its numbers, so they have no twins.
Two twins show how far exact agreement can be pushed. Chapter 7 computes with Python's math.lgamma, which is CPython's own approximation rather than the C library's log-gamma that Octave's gammaln calls, so its twin carries a copy of CPython's code. The CPython built for Apple silicon appears to be compiled so that a multiply followed by an add in that code becomes one fused operation, rounded once rather than twice, which is an inference from the twin's results rather than something CPython documents. Core Octave has no fused multiply-add function, so the twins of chapters 7 and 9 compute the fused result exactly from ordinary operations, which is known to be possible [22]. On a machine whose CPython does not fuse, the two routes could differ in the last bit of such a result, far below the nine digits a check prints.
08.Looking Ahead
With both routes installed, the book's front matter is complete. Part I opens with Why Codes Exist, whose script ch01_why_codes_exist.py and twin ch01_why_codes_exist.m are the first pair a reader runs, and from there every chapter's opening names both.
09.Worked Examples
10.Exercises
References
- [1]GNU Octave Project “Download.” octave.org. Read 2026-11-14. https://octave.org/download
- [2]GNU Octave Project “Octave for macOS.” Octave Wiki. Read 2026-11-14. https://wiki.octave.org/Octave_for_macOS
- [3]GNU Octave Project “Octave for GNU/Linux.” Octave Wiki. Read 2026-11-14. https://wiki.octave.org/Octave_for_GNU/Linux
- [4]GNU Octave Project “Octave for Microsoft Windows.” Octave Wiki. Read 2026-11-14. https://wiki.octave.org/Octave_for_Microsoft_Windows
- [5]GNU Octave Project “Command Line Options.” GNU Octave Manual, version 11.3.0. Read 2026-11-14. https://docs.octave.org/latest/Command-Line-Options.html
- [6]GNU Octave Project “Script Files.” GNU Octave Manual, version 11.3.0. Read 2026-11-14. https://docs.octave.org/latest/Script-Files.html
- [7]Python Software Foundation “random: Generate pseudo-random numbers.” The Python 3 documentation. Read 2026-11-14. https://docs.python.org/3/library/random.html
- [8]IEEE (2019). “IEEE Standard for Floating-Point Arithmetic.” IEEE Std 754-2019. doi:10.1109/IEEESTD.2019.8766229
- [9]Python Software Foundation “Floating-Point Arithmetic: Issues and Limitations.” The Python 3 documentation. Read 2026-11-14. https://docs.python.org/3/tutorial/floatingpoint.html
- [10]GNU Octave Project “Integer Arithmetic.” GNU Octave Manual, version 11.3.0. Read 2026-11-14. https://docs.octave.org/latest/Integer-Arithmetic.html
- [11]Python Software Foundation “Expressions.” The Python 3 documentation. Read 2026-11-14. https://docs.python.org/3/reference/expressions.html
- [12]Python Software Foundation “Built-in Functions.” The Python 3 documentation. Read 2026-11-14. https://docs.python.org/3/library/functions.html
- [13]GNU Octave Project “Utility Functions.” GNU Octave Manual, version 11.3.0. Read 2026-11-14. https://docs.octave.org/latest/Utility-Functions.html
- [14]Python Software Foundation “math: Mathematical functions.” The Python 3 documentation. Read 2026-11-14. https://docs.python.org/3/library/math.html
- [15]GNU Octave Project “Bit Manipulations.” GNU Octave Manual, version 11.3.0. Read 2026-11-14. https://docs.octave.org/latest/Bit-Manipulations.html
- [16]GNU Octave Project “Special Utility Matrices.” GNU Octave Manual, version 11.3.0. Read 2026-11-14. https://docs.octave.org/latest/Special-Utility-Matrices.html
- [17]GNU Octave Project “GNU Octave Version 7.” octave.org. Read 2026-11-14. https://octave.org/NEWS-7.html
- [18]GNU Octave Project “JSON data encoding/decoding.” GNU Octave Manual, version 11.3.0. Read 2026-11-14. https://docs.octave.org/latest/JSON-data-encoding_002fdecoding.html
- [19]Python Software Foundation “json: JSON encoder and decoder.” The Python 3 documentation. Read 2026-11-14. https://docs.python.org/3/library/json.html
- [20]Python Software Foundation “subprocess: Subprocess management.” The Python 3 documentation. Read 2026-11-14. https://docs.python.org/3/library/subprocess.html
- [21]GNU Octave Project “Controlling Subprocesses.” GNU Octave Manual, version 11.3.0. Read 2026-11-14. https://docs.octave.org/latest/Controlling-Subprocesses.html
- [22]Boldo, Sylvie and Melquiond, Guillaume (2008). “Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd.” IEEE Transactions on Computers, 57(4), pp. 462–471. doi:10.1109/TC.2007.70819
— Anirban
Hardware–software at the seam where compilers meet microcode.