Chapter 12
bc and dcIn This Chapter
@) eventually runs out of roadbc calls, the REPL, and running scripts from filesbc as a real little language: variables, control flow, user functionsbc from cshw scripts — the killer integration storydc — the reverse-Polish sibling, on the same arithmetic backendbc -x) — rationals, symbolic sqrt, "exact when possible"bc -c) — Gaussian arithmetic for EE/physics usebc -x extension) — small symbolic linear algebra@, when for bc, when for dcChapter 5 introduced @ for arithmetic — fast, in-process, integer- and float-typed. For 95% of "I need a number" jobs, @ is the right tool. But @ is 64-bit IEEE-754 underneath, which means it eventually trips over the limits of binary floating-point: rounding error in long calculations, silent overflow in big integers, and "0.1 + 0.2 != 0.3" surprises in any field that does money or decimals.
That's where bc and dc come in. Both are arbitrary-precision calculators — numbers as big as you want, decimals as accurate as you want, no float-format loss. They're built into cshw on top of Gavin Howard's BCL library, with their own lexers, parsers, and interpreters. bc reads infix expressions like a calculator or a programming language; dc reads reverse-Polish stack commands like an HP calculator. Different surfaces, same arithmetic engine.
This chapter teaches both. By the end, you'll know when shell math is enough, when you need bc's precision, and when dc's stack model is the cleaner fit.
Before we get into the why, here's what the three calculators look like side by side. Type these at any cshw prompt — they all work right now, no setup, no installs.
> bc "0.1 + 0.2"
.3
> bc "scale=20; 4 * a(1)"
3.14159265358979323844
> bc -x "1/3 + 1/6"
1/2
> bc -x "sqrt(2) * sqrt(2)"
2
> dc -e "5 2 + p"
7
> dc -e "10 3 2k / p"
3.33
Three different surfaces, one shared arithmetic backend:
| Tool | Surface | Default precision |
|---|---|---|
bc |
Infix expressions, like a calculator or a small programming language | Decimal, scale 20 (20 digits past the point) |
bc -x |
The same surface, plus exact rationals and symbolic sqrt |
1/3 stays 1/3, not .333…; sqrt(2)*sqrt(2) collapses to 2 |
dc |
Reverse-Polish — operands first, operator last, p prints the top of stack |
Decimal, scale 20 — the same default as bc. Drop to integer with 0k; hex output with 16o |
If those examples already make sense to you, you can skim the rest of the chapter looking for the bits you want. If they don't, that's fine — we build up to each one. Either way, by the end of the chapter you'll know which tool to reach for and why.
@?A small demo to motivate the chapter.
@ a = 0.1 + 0.2
echo $a
Run that and you get 0.3 — but only because cshw's float formatter trims the trailing digits. The real answer in IEEE-754 is 0.30000000000000004, and operations that build on it accumulate error. For most purposes, fine. For financial calculations, for science, for anything where the answer needs to be exact to many digits, "fine" isn't good enough.
bc handles the same calculation with no rounding:
bc "0.1 + 0.2" # exactly 0.3
bc "scale=50; 1/3" # .33333333333333333333333333333333333333333333333333
bc "2^200" # full 61-digit integer answer, no overflow
Numbers in bc are arbitrary-precision decimal. Set the scale to however many fractional digits you want; integers grow to whatever size they need. The cost is speed (much slower than native floats) and the fact that you're shelling out to a different language for the math. For the cases where it matters, those costs are nothing.
REMEMBER
@ is for math you'd otherwise do in your head ("how many more iterations?"). bc is for math you'd otherwise do in a spreadsheet or a financial calculator ("compound interest over 30 years, to the cent"). Pick by what kind of answer you need.
bc: The Quick TourThe simplest form takes an expression on the command line and prints the answer:
bc "1 + 2 * 3" # 7
bc "100 / 7" # 14.28571428571428571428 (scale=20 default)
bc "sqrt(2)" # 1.41421356237309504880
bc "2^100" # 1267650600228229401496703205376
cshw's bc defaults to scale=20 (twenty fractional digits) and bases ten in / ten out. Override per call with -e, which lets you stack multiple statements:
bc -e "scale = 50" -e "1/3"
# .33333333333333333333333333333333333333333333333333
For longer programs, save to a file and run with -f:
bc -f myscript.bc
bc -f setup.bc -f compute.bc # multiple files in order
For interactive use, run bc with no arguments. You get a REPL:
bc
bc> 2 + 2
4
bc> scale = 30
bc> 1/7
.142857142857142857142857142857
bc> quit
Type quit (or halt) to return to cshw. Multi-line definitions accumulate until braces balance — handy for typing in functions interactively.
TRY IT
From the prompt, run bc "sqrt(2) * sqrt(2)". You'll get something like 1.99999999999999999999 (close to 2 but not exactly, because sqrt(2) is irrational and bc is computing it numerically). Now run bc -x "sqrt(2) * sqrt(2)". You'll get an exact 2. We'll see why in the Exact Mode section at the end of the chapter.
bc Is a Real Little Languagebc isn't just a calculator — it's a small programming language with variables, control flow, functions, and arrays. POSIX defines the surface; cshw implements all of it.
scale/ibase/obaseAssignment is =. Three special variables are built in:
scale — fractional digits used by division and the math library (default 20)ibase — input base (default 10)obase — output base (default 10)bc "scale=10; 1/7" # .1428571428
bc "obase=2; 10" # 1010 (decimal 10 in binary)
bc "obase=16; 255" # FF (decimal 255 in hex)
bc "ibase=16; FF" # 255 (hex FF in decimal)
Compound assignment works (+=, -=, *=, /=, %=, ^=), as does pre- and post-increment/decrement:
bc "x = 5; x += 3; x" # 8
bc "n = 10; n--" # 10 (postfix returns OLD value)
bc "n = 10; --n" # 9 (prefix returns NEW value)
WARNING
The classic POSIX bc gotcha: ibase and obase interact in confusing ways when you set both. Once ibase is non-10, every number you type — including the next number you assign to obase — is read in the new base. The canonical workaround is to use the standalone uppercase letters A-F, which always represent their constant value regardless of the current base. So ibase=A always means "set ibase to 10" no matter what state ibase was in. Burn this idiom into your fingers; everyone learning bc discovers the gotcha the hard way at least once.
if/else, while, for, break, continue — all where you'd expect them:
bc "for (i = 1; i <= 5; i++) i * i"
# 1
# 4
# 9
# 16
# 25
bc "n = 10; while (n > 0) { print n, \" \"; n-- }; print \"\\n\""
# 10 9 8 7 6 5 4 3 2 1
A bare expression statement prints its value automatically (the "calculator" half of bc), unless you're inside a function body — there, you use print or return explicitly.
bc "define f(n) { if (n < 2) return n; return f(n-1) + f(n-2) }; f(20)"
# 6765
That's a recursive Fibonacci. Functions are define NAME(PARAMS) { BODY }, with auto declarations at the top of the body for local variables. Use void to declare a function that doesn't return a value (skips the "print return value" auto-display).
For anything more than a one-liner, put your definitions in a .bc file and run with bc -f. Here's a small number-theory library:
# nt.bc — number-theory helpers
define gcd(a, b) {
auto t
while (b != 0) {
t = b
b = a % b
a = t
}
return a
}
define lcm(a, b) {
return a * b / gcd(a, b)
}
define is_prime(n) {
auto i
if (n < 2) return 0
if (n == 2) return 1
if (n % 2 == 0) return 0
for (i = 3; i * i <= n; i = i + 2) {
if (n % i == 0) return 0
}
return 1
}
Then from cshw:
bc -f nt.bc -e "gcd(123456789, 987654321)" # 9
bc -f nt.bc -e "lcm(12, 18)" # 36
bc -f nt.bc -e "is_prime(2147483647)" # 1 (a Mersenne prime, 2^31 - 1)
bc -f nt.bc -e "is_prime(2147483649)" # 0
A real little library, in twenty lines of .bc. The bc -f LIB.bc -e "EXPR" pattern — load a library, then ask one question — is the bread and butter of using bc from scripts.
TECHNICAL STUFF
bc's arrays are sparse — a[1000000] is fine; no memory is allocated for indices you don't touch. Arrays are referenced as NAME[index] and passed to functions by adding [] to the parameter name (define sum(a[], n)). This is exact POSIX behavior; arrays are also visible across function calls if not declared auto.
WARNING
Inside a function body, the order matters: auto declarations must come first, before any other statement. Putting an auto line in the middle of the body is a parse error. This is POSIX and it's why every example above puts auto t (or auto i) at the very top of the body.
scale for DisplayCompound interest is the canonical motivating example for bc because it shows off exactly why arbitrary-precision matters. cshw's bc carries full precision through ^ internally — the value is correct regardless of scale. The only question is how many digits you want to display.
The straightforward call:
bc "scale=2; 10000 * (1 + 0.05)^30"
# 43219.423751506620091572881988864733414733782410621643066406250000
That's $43,219.42… with a long mantissa trailing because the ^ operator kept enough precision to be exact, and the multiplication propagated all of it. The value is right; the display is verbose.
For a clean two-decimal display, use the bc idiom r / 1:
bc "scale=2; r = 10000 * (1 + 0.05)^30; r / 1"
# 43219.42
Division applies scale, so r / 1 truncates the value to the current scale's worth of fractional digits. The whole expression reads as: compute, store, format.
For library code that returns currency, wrap the format step inside the function:
# finance.bc — compound interest helpers
define future_value(principal, rate, periods) {
return principal * (1 + rate)^periods
}
define monthly_payment(principal, annual_rate, years) {
auto r, n, factor
r = annual_rate / 12
n = years * 12
factor = (1 + r)^n
return principal * r * factor / (factor - 1)
}
Then:
bc -f finance.bc -e "scale=2; future_value(10000, 0.05, 30) / 1"
# 43219.42
bc -f finance.bc -e "scale=2; monthly_payment(300000, 0.065, 30) / 1"
# 1896.20
The caller controls display precision via scale; the function bodies stay clean.
TIP
^ keeps enough precision internally that the result is always correct, no matter what scale is set to. scale controls only how many digits print, not how the arithmetic is carried — so compound-interest calculations don't silently drift. Use r / 1 to truncate to a clean display when you need it.
bc from cshw ScriptsThe killer feature for shell users isn't bc itself — it's bc-in-a-pipeline. Capturing bc's output into a cshw variable, using it in the next command, threading it through a longer pipeline. The mechanism is the standard backtick (or $(...)) command substitution from Chapter 5:
set tax = `bc "scale=2; $price * 0.0825"`
set monthly = `bc -x "1/12"`
set pi = $(bc "scale=10; 4 * a(1)")
Each bc call is a fresh process — invocation cost is small, but real. For one calculation it's not noticeable; for a thousand calls in a tight loop, it adds up. The right pattern is to do one heavy bc call that returns everything you need, rather than many small ones.
A real-world example — a script that takes a sales CSV and computes per-row tax and a total:
# tax_calc.cshw
set total = 0
foreach line (`type sales.csv`)
set price = $(echo $line | cut -d, -f3)
set tax = `bc "scale=2; $price * 0.0825"`
set total = `bc "scale=2; $total + $price + $tax"`
echo "$line,$tax"
end
echo "Final total: $total"
Each line: extract price, compute tax, add to running total. Three bc calls per row, all under a millisecond each, total time fine for any spreadsheet-sized input.
For bulk numeric processing — millions of rows, tight inner loops, anywhere latency adds up — the right pattern is to push the loop into bc:
# Get the total inside bc, not one row at a time
set sum = `type sales.csv | bc -e "scale=2; s=0" -e "while (s = s + ?) ; s"`
That uses bc's read-from-stdin behavior (? reads one number from stdin) to do the entire accumulation inside one bc invocation. One process, one parse, one execution. For large inputs, the speedup is dramatic.
TIP
A useful idiom for "do precise math, but want an integer back to use as a shell counter": pipe through bc to round explicitly, then capture. set n = $(bc "scale=0; 42.7 / 1") gives you 42 (scale=0 truncates), which @ can then operate on as a normal integer.
TECHNICAL STUFF
bc writes its results to stdout; errors go to stderr. So set v = $(bc "..." 2>/dev/null) suppresses error messages (useful in scripts where you've already validated the input). For scripts that need to detect a bc failure, check $? afterward — bc returns non-zero on syntax errors or division by zero.
bc ships with a standard math library that's loaded automatically. The POSIX names are short:
| POSIX function | Meaning |
|---|---|
e(x) |
e^x |
l(x) |
natural logarithm |
s(x) |
sine (radians) |
c(x) |
cosine (radians) |
a(x) |
arctangent (radians) |
j(n, x) |
Bessel function of the first kind, order n |
Those one-letter names date from the 1970s and they bite anyone coming from a modern language. cshw adds a friendly alias layer on top so the names you'd actually reach for also work:
| cshw alias | What it computes |
|---|---|
sin(x), cos(x), tan(x) |
Trigonometric — s(x), c(x), s(x)/c(x) |
asin(x), acos(x), atan(x) |
Inverse trig — via a() |
atan2(y, x) |
Full-quadrant arctangent |
exp(x), ln(x) |
e(x) and l(x) |
log(x), log10(x), log2(x) |
Base-converted from l() |
pi() |
π to the current scale |
Examples:
bc "pi()" # 3.14159265358979323844
bc "sin(pi()/2)" # 1.00000000000000000000
bc "ln(2)" # .69314718055994530941
bc "log10(1000)" # 3.00000000000000000000
The aliases are real bc defines living alongside the standard library; you can read or override them in your own scripts if you want. They exist purely to make bc less hostile to people who've used a scientific calculator anytime in the last fifty years.
dc: The Reverse-Polish Siblingdc is older than bc — it shipped on the PDP-7 in 1970, and bc was originally a preprocessor that translated infix syntax into dc commands. Today they're separate programs, but they share an arithmetic backend in cshw, and the relationship is still visible if you squint.
If you've used an HP calculator, RPN math feels natural: instead of writing 2 + 3, you push 2, push 3, then add. The advantage is no operator precedence and no parentheses — everything is explicit, left to right.
dc maintains a value stack. Numbers push onto it; commands operate on the top.
dc "1 2 +p" # push 1, push 2, add (replaces top two with 3), p prints top
# 3
dc "3 4 5 + *p" # push 3, push 4, push 5, add (4+5=9), multiply (3*9=27), print
# 27
dc "2 10 ^p" # 2^10 = 1024
# 1024
Single characters do the work: +, -, *, /, %, ^ for arithmetic; p prints the top of stack without popping; n prints and pops; f prints the entire stack.
d duplicate topr swap top twoc clear stackz push the stack's current depth (handy for diagnostics)dc "1 2 3 dp" # push 1 2 3, duplicate top, print -> 3
dc "5 3 rp" # push 5 3, swap (now 3 5), print -> 5
dc "1 2 3 z p" # push 1 2 3, push stack depth (3), print -> 3
dc "3 d* 4 d* + vp"
# 5.00000000000000000000
dc "0k 3 d* 4 d* + vp"
# 5
Reading that: push 3, duplicate-and-multiply (= 9), push 4, duplicate-and-multiply (= 16), add (= 25), square root, print. Five characters of stack manipulation compute sqrt(3^2 + 4^2) = 5.
The trailing zeros are the scale-20 default doing its job — cshw's dc shares bc's decimal default rather than GNU dc's integer one, so the answer comes back to twenty places whether or not it needed them. 0k first if you want the bare integer. This is a deliberate divergence from GNU dc: within cshw the two calculators agree with each other, which matters more than matching a tool you are not running. The same calculation in infix would be sqrt(3*3 + 4*4) — slightly longer, slightly more punctuation, but the RPN version has a certain elegance once your eye is trained.
That's a fair sample of where dc shines: short expressions that are stack-friendly (each value gets used right after it's pushed) come out tight, often tighter than the infix equivalent.
dc's lexer treats - as the subtraction operator, so for negative literals you prefix with _ (underscore):
dc "_5 3 +p" # -5 + 3 = -2
# -2
dc "20k 2vp" # set scale to 20, push 2, sqrt, print -> 1.41421356237309504880
# 1.41421356237309504880
k sets scale (pops a value, makes that the new scale); K pushes the current scale. Same pattern for bases: i / I for ibase, o / O for obase.
dc "16o 255p" # set obase to 16, push 255, print -> FF
# FF
dc "2o 10p" # set obase to 2, push 10, print -> 1010
# 1010
Single-character registers let you stash a value (or a macro) for reuse. sR stores the top of stack into register R; lR loads register R back onto the stack.
dc "5 sn lnln*p" # store 5 in 'n', load 'n' twice, multiply, print -> 25
# 25
Macros are square-bracketed strings; x executes the macro at the top of stack. Combined with the conditional commands <R, >R, =R (and their negated !<R, !>R, !=R), you have a Turing-complete (if cryptic) programming environment:
dc "[1+]sa 5 lax p"
# 6
That stores the macro [1+] (add one) in register a, pushes 5, executes the macro (turns 5 into 6), and prints. Tiny, but it's the building block.
A recursive factorial:
dc "[d 1- d 1<f *]sf 5 lfx p"
# 120
Reading that: define macro f as "duplicate, subtract 1, duplicate, if-1-is-less-than-(n-1) run f recursively, multiply." Push 5. Run f. Print.
The condition 1<f follows POSIX dc semantics: <R fires when the top of the stack is less than the next-to-top. So with stack […, n-1, 1], <f recurses while 1 < n-1, terminating once n hits 1.
If that reads like line noise, you've correctly perceived dc's charm. RPN macros are a different way of thinking about computation — more like assembly than like algebra — and once you internalize the stack discipline, certain kinds of expressions are genuinely shorter to write in dc than in any infix language.
WARNING
dc is a write-only language. A six-line dc script you wrote last month will look like a riddle today. For anything you'll need to maintain, use bc. Save dc for one-shots, for stack-friendly expressions where the RPN form is genuinely clearer, and for the joy of speaking a 1970s calculator language at the modern shell prompt.
cshw's dc covers the POSIX core plus the register-array extensions (:R to store at index, ;R to load). A handful of GNU/OpenBSD dc commands aren't wired up in this release: ~ (quotient and remainder together), R (rotate the stack), Z (number of digits), X (number of fraction digits), S/L (named stacks), P (print as ASCII bytes), | (modular exponentiation). They may land in a future cshw version if there's demand.
bc -xThis is the section where bc stops being "a slow but accurate calculator" and starts being something more interesting — and it's the headline feature most people remember after reading the chapter.
Default bc arithmetic is scaled decimal — every result is a decimal number rounded to scale digits. That's enough for most work, but it means operations that should be exact are only approximate. 1/3 becomes .3333... with however many digits you asked for, and (1/3) * 3 rounds back to almost 1, off by a digit at the end.
With the -x (or --exact) flag, bc adds two more arithmetic layers on top of the BCL backend:
p/q pairs, kept exact and auto-reduced.Power(rational, rational) representation that carries symbolic powers (square roots, cube roots, integer powers, fractional powers) without ever evaluating them numerically.The result is that calculations stay exact when they can be exact, and fall through to ordinary scaled-decimal only when they truly can't.
bc -x "1/3 + 1/6" # 1/2 (exact rational sum)
bc -x "5/15" # 1/3 (auto-reduced)
bc -x "2^10" # 1024 (integer fold)
bc -x "(1/2)^3" # 1/8 (rational power)
bc -x "sqrt(2)" # 2^(1/2) (symbolic — kept as a Power)
bc -x "sqrt(2) * sqrt(2)" # 2 (same-base fold: 2^(1/2) * 2^(1/2) = 2^1)
bc -x "sqrt(8) / sqrt(2)" # 2 (8 = 2^3, so 2^(3/2) / 2^(1/2) = 2^1)
bc -x "cbrt(27)" # 3 (integer cube root recognized)
Variables work the same way — they hold whatever exact form they're assigned, and the form propagates through arithmetic:
bc -x "x = 1/3; y = 1/6; x + y" # 1/2
bc -x "r = sqrt(2); r * r" # 2
This is the one thing to pin down before you start expecting -x to do things it doesn't do.
-x is not a computer algebra system. It can hold an exact form, fold same-base powers, and reduce rationals. It cannot:
sqrt(2) + sqrt(3) falls through to a decimal approximationsin(1), exp(0.5), ln(2) all produce decimals(sqrt(2) + 1) * (sqrt(2) - 1) should be 1 before multiplying out — it has to evaluate the product mechanicallyConcrete examples of where -x falls back to decimal:
bc -x "sqrt(2) + sqrt(3)" # 3.14626436994197234... (decimal — no symbolic sum)
bc -x "sin(1)" # .84147098480789650665... (decimal — transcendental)
bc -x "exp(0.5)" # 1.64872127070012814685... (decimal — transcendental)
The contract is "exact when possible, decimal when not, never CAS." Three words to memorize. If you reach for -x expecting it to do symbolic algebra, you'll be frustrated; if you reach for it expecting exact rational and integer-power arithmetic, you'll be delighted.
For full symbolic math, you'd reach for Mathematica, SymPy, or a real CAS. bc -x is a sharp little tool for one specific job — exact decimal-free arithmetic — and it does that job extremely well.
TIP
-x shines for verification — confirming that a hand-derived formula simplifies the way you think it does. bc -x "1/2 + 1/3 + 1/6" returning 1 (and not .9999…) is the kind of check that catches a sign error in seconds. Note that bc -x "(sqrt(2)+1)*(sqrt(2)-1)" does not simplify to 1 -- the exact tier can't recognize that the cross terms cancel (that's CAS territory). It computes the multiplication numerically and returns .9999…99. Use -x to verify arithmetic that stays in form, not algebraic identities.
TECHNICAL STUFF
Internally, every value in -x mode is either an integer, a Rational(p, q), a Power(rational base, rational exponent), or a fallback BCL decimal. Operations are tried in that order — integer arithmetic stays integer, rational arithmetic stays rational, power arithmetic folds when bases match, otherwise the value falls through to BCL. The implementation is intentionally focused; future versions may grow more folding rules, but they will not grow into a full CAS.
bc -cThe other opt-in tier in cshw's bc is complex-number arithmetic, activated by -c (or --complex). It's pitched at electrical engineers (AC impedance), physicists (quantum mechanical amplitudes), and anyone who needs sqrt(-1) to return i instead of an error.
The four constructor/accessor built-ins are lowercase to dodge BCL's base-36 number parsing (where uppercase I lexes as 18, not as an identifier):
| Built-in | What it does |
|---|---|
cplx(re, im) |
Construct the complex number re + im*i |
re(z) |
Extract the real part |
im(z) |
Extract the imaginary part |
conj(z) |
Conjugate: cplx(a, b) → cplx(a, -b) |
abs(z) |
Magnitude: sqrt(re^2 + im^2) |
The imaginary unit is cplx(0, 1). There's no shortcut keyword — type the constructor.
Arithmetic on complex values behaves the way the math dictates:
bc -c "cplx(0, 1) * cplx(0, 1)" # -1 (i^2)
bc -c "cplx(1, 2) + cplx(3, 4)" # 4+6i
bc -c "cplx(3, 4) * cplx(1, 2)" # -5+10i
bc -c "cplx(1, 1) / cplx(1, -1)" # i
bc -c "sqrt(cplx(-4, 0))" # 2.00000000000000000000i (negative real -> pure imaginary)
bc -c "abs(cplx(3, 4))" # 5.00000000000000000000 (the 3-4-5 right triangle)
bc -c "conj(cplx(3, 4))" # 3-4i
Mix complex with real and the real value lifts automatically:
bc -c "cplx(3, 4) + 2" # 5+4i
bc -c "2 * cplx(0, 1)" # 2i
Output formatting drops zero parts and 1-coefficients the way handwritten math does:
bc -c "cplx(0, 0)" # 0
bc -c "cplx(5, 0)" # 5
bc -c "cplx(0, 1)" # i
bc -c "cplx(0, -1)" # -i
bc -c "cplx(3, -1)" # 3-i
bc -c "cplx(0, 5)" # 5i
WARNING
Complex numbers have no total order. bc -c "cplx(1, 2) < cplx(3, 4)" raises a runtime error, not a quiet boolean. Equality (==, !=) works because structural equality is well-defined; ordering operators don't, because you can't say "this complex is less than that complex" in any consistent way. Don't try to sort complex numbers.
-c composes with -x: in bc -x -c, real arithmetic stays exact (rationals, Power forms) and complex arithmetic happens at decimal precision. cshw may one day grow Gaussian-rational complex numbers (cplx(1/2, 1/3) staying exact), but for now the real and imaginary parts are scaled decimals.
TIP
For one-shot AC-impedance work, the -c mode is a one-liner. bc -c "z = cplx(50, -30); abs(z)" gives you the magnitude of a 50 - 30j Ω impedance in one call. For heavy numerical-linear-algebra workloads, reach for Python + NumPy via shell-out — bc is a sharp little tool, not a replacement for a full numerics environment.
Inside -x mode, bc gains small-matrix linear algebra with exact-rational entries. The motivating use case: doing 3x3 / 4x4 determinants and inverses BY HAND, where rounding can compound across many operations. Sympy would also do this; the difference is bc -x is already in your shell.
The syntax is bracketed nested lists:
bc -x "[[1, 2], [3, 4]]" # 2x2
bc -x "[[1, 2, 3], [4, 5, 6]]" # 2x3
bc -x "[[1], [2], [3]]" # 3x1 column vector
bc -x "[[1/2, 1/3], [1/4, 1/5]]" # rational entries
Arithmetic works the way you'd expect:
bc -x "[[1, 2], [3, 4]] + [[5, 6], [7, 8]]" # [[6, 8], [10, 12]]
bc -x "[[1, 2], [3, 4]] * [[5, 6], [7, 8]]" # [[19, 22], [43, 50]]
bc -x "3 * [[1, 2], [3, 4]]" # [[3, 6], [9, 12]]
bc -x "-[[1, 2], [3, 4]]" # [[-1, -2], [-3, -4]]
Built-in functions cover the standard small-matrix toolkit:
| Function | Returns |
|---|---|
det(M) |
determinant (M must be square) |
transpose(M) |
M's transpose |
inverse(M) |
M's inverse via Gauss-Jordan elimination |
mget(M, i, j) |
the entry at row i, col j (0-indexed) |
mset(M, i, j, v) |
a new matrix with entry (i,j) replaced |
rows(M) / cols(M) |
dimensions |
The hallmark of this tier is that entries stay exact through every operation. Invert a matrix of integers and you get a matrix of rationals; multiply it back and you get the identity:
bc -x "m = [[4, 7], [2, 6]]; inverse(m)" # [[3/5, -7/10], [-1/5, 2/5]]
bc -x "m = [[4, 7], [2, 6]]; m * inverse(m)" # [[1, 0], [0, 1]]
bc -x "det(inverse([[4, 7], [2, 6]]))" # 1/10 (= 1/det(M))
That [[3/5, -7/10], [-1/5, 2/5]] is the true inverse, not a floating-point approximation. The Gauss-Jordan elimination runs over rationals; every operation is Rational(p, q) arithmetic. No numerical methods are involved because no numerical methods are needed.
WARNING
Single uppercase letters lex as base-36 digit values (per BCL's number lexer), so M = [[1, 2], [3, 4]] is not a valid assignment in cshw's bc — M parses as the literal 22. Use lowercase variable names: m = [[1, 2], [3, 4]]. Same gotcha as I for the complex imaginary unit.
This is not a numerical linear algebra library. There are no eigenvalues, no LU/QR/SVD, no condition-number checks. The implementation is small (Gauss-Jordan over rationals, cofactor expansion for determinant) and the scope is intentionally narrow:
1.5 in a literal in -x mode it stays as Rational(3, 2); but if you somehow get a Power(2, 1/2) into a matrix slot, the literal parser will reject it.apply(sin, M) to take sin of every entry. (Trivially scriptable in cshw if you really want it.)bc -x "det([[..., ..., ..., ...], ...])" checks instantly.Ax = b (via inverse(A) * b) where every entry is a rational probability.For everything else, the shell-out pattern still works:
set det = `py -c "import numpy as np; print(np.linalg.det([[1,2,3],[4,5,6],[7,8,10]]))"`
echo "Python says det = $det"
bc isn't trying to replace Python here. It's trying to be useful for the small fraction of linear-algebra work where exactness matters more than scale.
@ vs bc vs dcThis is probably the section of the chapter you'll come back to. Bookmark it.
| Use... | When |
|---|---|
@ |
The math is short, the precision is "approximately right," and speed matters. Loop counters, array indices, percentage display, anything you'd compute in your head if it weren't for the variable. Integer and float, but no rationals — @ is IEEE-754 underneath. |
bc |
You need exact decimal answers, big integers, or many fractional digits. Money, science, statistics. Or when you want a real programming language for the math part of your script. |
bc -x |
You're working with exact rationals, integer powers, or expressions where same-base square-root folding matters. This is also where you go when @ would have done rationals — 1/3 as 1/3 rather than 0.333... only lives in bc -x. Algebraic verification, exact-fraction work, anything that should stay a fraction rather than degrade to a decimal. |
dc |
You think in RPN; the expression is stack-friendly; or you're writing a one-shot calculation where dc's terseness wins. (For maintainable code, prefer bc.) |
A common pattern in real scripts: use @ for the orchestration (counters, comparisons, simple sums) and shell out to bc for the substantive math. The latency of invoking bc is small enough that you won't notice for occasional calls; for tight inner loops, @ is the right choice.
# A script that uses both
@ row_count = 0
foreach line (`type sales.csv`)
@ row_count = $row_count + 1 # @ for counting
# ... extract amount, accumulate in $total ...
end
set average = `bc "scale=2; $total / $row_count"` # bc for the precision-sensitive math
echo "Processed $row_count rows, average: $average"
A few things to know:
bc "EXPR" is a fresh process; variables and definitions set in one call don't survive into the next. The standard workaround is backtick capture in cshw — compute once, capture into a shell variable, reuse: set rate_factor = `bc "scale=20; (1 + 0.05)^30"`
set fv_10k = `bc "scale=2; 10000 * $rate_factor / 1"`
set fv_50k = `bc "scale=2; 50000 * $rate_factor / 1"`
The rate_factor lives in cshw between calls; each bc invocation does just one piece of math. For a library of definitions, use bc -f LIB.bc -e "EXPR" so the library reloads each time without your script needing to remember its definitions.
for loop in bc that does a thousand iterations of 1/3 is not fast. Profile before assuming bc will work for any tight inner loop; it usually won't.bc -c does Gaussian arithmetic but at decimal precision (no exact Gaussian rationals yet), and bc -x's matrix tier is small-matrix, rational-entry only — no eigenvalues, SVD, or float/complex matrices. See the Complex Mode and Exact Matrix Arithmetic sections above for exactly where each falls back. For heavy numerical linear algebra, drop to Python + NumPy.dc is the shorter list of features. dc operates on real numbers only (complex is a bc -c feature), and several GNU/OpenBSD extensions (~, R, Z, X, ;, :, S, L, P, |) aren't implemented. POSIX-core dc programs work; programs depending on those extensions don't.For most "I need accurate math from the shell" tasks, none of those limits bite. When they do, you've outgrown what shell-bundled calculators can do, and a real numeric environment (NumPy, R, Mathematica, etc.) is the right tool.
REMEMBER
bc and dc are built into cshw. No external install, no PATH dependency, no version skew. The same scripts run on every cshw install, with the same arithmetic backend (Gavin Howard's BCL), with the same exact-mode rules. That portability is worth a lot in scripting — you're not betting on whether the user's system happens to have bc installed and which dialect it speaks.
You now have a real arithmetic platform in the shell — arbitrary-precision decimal for everyday math, an RPN sibling for stack-friendly one-shots, and exact rationals with symbolic-power folding for the cases where decimal isn't good enough. Combined with the rest of cshw's scripting toolkit, you can write financial scripts, scientific data processors, exact-arithmetic verifiers, and anything else where "the answer is approximately right" isn't good enough.
The next chapter returns to the shell-as-platform thread — Chapter 13 covers job control, the small but well-loved vocabulary for managing background work. After that, Part IV opens with coroutines, networking, AI integration, and plugins — the chapters that show off what makes cshw more than a Unix shell ported to Windows.
For now, take any calculation you've been doing in a spreadsheet or a calculator app and try it in bc instead. The moment a thirty-line spreadsheet formula becomes a five-line .bc library you can call from any script is the moment bc earns its keep.