Mathbook Manual

Mathbook evaluates JavaScript expressions with extra calculator, binary, plotting, signal, and FFT helpers.

Showing all sections.

Basics

Type a JavaScript expression and press Eval. Use the Plot button to graph expressions over the X range shown in the controls.

2 + 3 * 4
sin(pi / 4)
a = 12
a * 10

Assignments like a = 12 are saved for later inputs. Prefer direct assignments for reusable values; block-local JavaScript declarations such as let are not meant as notebook variables.

Useful JavaScript In Mathbook

Because Mathbook evaluates JavaScript, ordinary JavaScript operators, arrays, strings, objects, arrow functions, loops, and Math methods are available.

Operators

PatternUseExamples
+, -, *, /, %, **Arithmetic, remainder, and exponentiation.2 ** 10 -> 1024
17 % 5 -> 2
<, <=, >, >=, ===, !==Comparisons. Prefer strict equality ===.3 * 3 === 9 -> true
&&, ||, !Boolean logic.5 > 3 && 2 < 4 -> true
condition ? yes : noInline conditional expression.X < 0 ? -1 : 1
&, |, ^, ~, <<, >>, >>>Native JavaScript 32-bit bitwise operators. Mathbook also has named helpers such as and() and xor().hex((0xf0 & 0xcc) >>> 0)

Variables, Functions, And Loops

a = 42
b = hex(a)
square = x => x * x
square(12)

sum = 0; for (i = 1; i <= 10; i++) sum += i; sum

fact = n => n <= 1 ? 1 : n * fact(n - 1)
fact(6)

Arrays

PatternUseExamples
[...]Create an array.[1, 2, 3]
array.lengthNumber of items.[10,20,30].length -> 3
array[index]Read or write by zero-based index.a = [9,8,7]; a[1] -> 8
map(fn)Transform every item.range(0,5).map(x => x*x)
filter(fn)Keep matching items.range(0,10).filter(x => x % 2 === 0)
reduce(fn, seed)Fold an array to one value.range(1,6).reduce((a,b) => a+b, 0) -> 15
slice(start, end)Copy part of an array.range(0,10).slice(2,5)
join(text)Join values into a string.[1,2,3].join(", ")

Strings

"hello".toUpperCase()
"A,B,C".split(",")
"ABC".split("").map(ord)
[72,101,108,108,111].map(asc).join("")

Objects And JSON

point = { x: 3, y: 4 }
sqrt(point.x * point.x + point.y * point.y)
JSON.stringify(point)
JSON.parse('{"x":3,"y":4}').x

Useful Math Methods

MethodUseExamples
Math.floor(x), Math.ceil(x), Math.round(x)Round numbers down, up, or to nearest integer.Math.round(3.6) -> 4
Math.min(...values), Math.max(...values)Minimum and maximum. Use spread syntax for arrays.Math.max(...[4,8,2]) -> 8
Math.random()Random number from 0 inclusive to 1 exclusive.Math.floor(Math.random() * 6) + 1
Math.atan2(y, x)Angle from X axis to point (x,y).Math.atan2(1, 1)
Math.PI, Math.EBuilt-in constants. Mathbook also exposes pi.Math.E ** 2

Conversion And Text

FunctionWhat it doesExamples
int(value, base)Converts numbers, booleans, and strings to integers. Without base, prefixes 0x, 0b, and 0o are detected. Base may be 2 through 36.int("0xff") -> 255
int("1010", 2) -> 10
int(4.9) -> 4
hex(value)Formats an integer as uppercase hexadecimal with a 0x prefix. Arrays are converted element by element.hex(255) -> 0xFF
hex([10,15])
bin(value)Formats an integer as binary with a 0b prefix. Arrays are converted element by element.bin(10) -> 0b1010
dec(value)Converts a value to a decimal integer. Arrays are converted element by element.dec("0b1111") -> 15
oct(value)Formats an integer as octal with a 0o prefix. Arrays are converted element by element.oct(64) -> 0o100
asc(value)Returns the character for the low 16 bits of an integer. Arrays are converted element by element.asc(65) -> A
asc([72,73])
ord(value)Returns the UTF-16 code unit of the first character in a non-empty string. Arrays are converted element by element.ord("A") -> 65

Bitwise And Binary Utilities

FunctionWhat it doesExamples
bits(value)Returns an array of set bit indexes for a 32-bit unsigned value. Bit 0 is the least significant bit.bits(10) -> [1,3]
and(a, b, ...)Bitwise AND across two or more values. You may also pass one array.and(0xf0, 0xcc) -> 192
and([7,3,1]) -> 1
or(a, b, ...)Bitwise OR across two or more values. You may also pass one array.or(0x80, 0x0f) -> 143
xor(a, b, ...)Bitwise XOR across two or more values. You may also pass one array.xor(0xff, 0x0f) -> 240
not(value)Bitwise NOT as an unsigned 32-bit result.hex(not(0)) -> 0xFFFFFFFF
crc32(bytes)Computes CRC-32 for an array of byte values. Each byte is masked to 0..255.hex(crc32([65,66,67]))
dword2float(value)Interprets a 32-bit integer as an IEEE-754 single precision float.dword2float(0x3f800000) -> 1
float2dword(value)Converts a JavaScript number to IEEE-754 single precision bits in a 32-bit integer.hex(float2dword(1)) -> 0x3F800000

Math Functions And Constants

NameWhat it doesExamples
sin(x), cos(x), tan(x)Trigonometric functions in radians.sin(pi / 2) -> 1
sqrt(x), abs(x)Square root and absolute value.sqrt(81) -> 9
abs(-4) -> 4
log(x), log10(x), exp(x)Natural logarithm, base-10 logarithm, and e raised to a power.log(exp(2)) -> 2
log10(1000) -> 3
piThe value of Math.PI.2 * pi
C0Speed of light in vacuum, in meters per second.C0 / 1e6 -> 299.792458

Arrays And Element-Wise Operations

Many signal helpers accept arrays. Element-wise math helpers accept arrays, signals, and scalars. When both inputs are arrays or signals, their lengths must match.

FunctionWhat it doesExamples
range(start, stop, step)Creates values from start up to but not including stop. step defaults to 1 and may be negative.range(0, 5) -> [0,1,2,3,4]
range(5, 0, -2)
linspace(start, stop, count)Creates count evenly spaced values from start to stop, inclusive.linspace(0, 1, 5) -> [0,0.25,0.5,0.75,1]
zeros(length)Creates an array of zeroes of the requested length.zeros(4) -> [0,0,0,0]
add(a, b)Adds scalars, arrays, or signals element by element.add([1,2], 10) -> [11,12]
sub(a, b)Subtracts scalars, arrays, or signals element by element.sub([5,6], [1,2])
mul(a, b)Multiplies scalars, arrays, or signals element by element.mul([1,2,3], 4)
div(a, b)Divides scalars, arrays, or signals element by element.div([10,20], 10)
pow(a, b)Raises values to powers element by element.pow([2,3,4], 2)
dot(a, b)Returns the dot product of same-length arrays or signals.dot([1,2,3], [4,5,6]) -> 32
mean(value)Average of finite values in an array or signal. Non-finite values are ignored.mean([1,2,3]) -> 2
polyfit(x, y, degree)Fits a polynomial of the given degree to the data and returns coefficients in descending-power order, like MATLAB.polyfit([0,1,2], [1,3,7], 2)
polyval(coeffs, x)Evaluates a polynomial given descending-power coefficients at a scalar, array, or signal.polyval([2,3,4], 5) -> 69
detrend(value, order)Removes a trend from an array or signal. order = 0 removes the mean, order = 1 removes a linear trend. Default is 1.detrend([1,2,3,4])
detrend([5,6,7], 0)

Signals And Windows

A signal stores samples plus metadata: starting X value x0, sample spacing dx, and a label. Signals display as signal(len=..., x0=..., dx=...).

FunctionWhat it doesExamples
discrete(fn, start, stop, step)Samples an arrow/function at points from range(start, stop, step) and returns a signal.discrete(x => sin(x), 0, 2*pi, 0.1)
load_csv(text[, x0, dx])Parses delimited numeric text into one signal per column. Commas, semicolons, tabs, and whitespace are accepted as separators. Rows containing A-Z or a-z are skipped.cols = load_csv("time,value\n0,1\n1,2")
plot(cols[1])
hanning(nOrSignal)Creates a Hann window. If given a signal, signal metadata is preserved.hanning(8)
hamming(nOrSignal)Creates a Hamming window.hamming(8)
blackman(nOrSignal)Creates a Blackman window.blackman(8)
rect(nOrSignal)Creates a rectangular window of ones.rect(8)
zero_pad(value, length)Pads an array or signal with zeroes to length. Length must be at least the current length.zero_pad([1,2,3], 8)
remove_dc(value)Subtracts the mean from an array or signal.remove_dc([9,10,11])
s = discrete(x => sin(2*pi*x), 0, 1, 0.01)
w = hanning(s)
windowed = mul(s, w)

Converting Signals And Spectra To And From Arrays

Signals and spectra are plain JavaScript objects with special marker fields. You can inspect or build them directly when you need exact control.

Signal To Array

s = discrete(x => sin(x), 0, 1, 0.25)
y = s.y
x_values = range(0, s.y.length).map(i => s.x0 + i * s.dx)
plain_copy = s.y.slice()

Array To Signal

arr = [1, 3, 2, 5]
s1 = discrete((x, i) => arr[i], 0, arr.length, 1)
s2 = ({ __mathbookType: "signal", y: arr, x0: 10, dx: 0.5, label: "manual signal" })
plot(s2)

Use discrete() for a quick signal from an array. Use the object form when you want custom x0, dx, or label. Wrap object literals in parentheses so JavaScript treats them as expressions.

Mapping Every Value

Arrays use normal JavaScript .map(fn). Mathbook signals and spectra also support direct .map(fn).

[1,2,3,4].map(sin)

s = discrete(x => x, 1, 5, 1)
s.map(sin)

sp = fft([1,2,3,4])
sp.map((re, im, i) => [re * 2, im * 2])

Spectrum To Arrays

sp = fft([1, 2, 3, 4])
real_bins = sp.re
imag_bins = sp.im
frequency_bins = freqs(sp)
magnitude = mag(sp).y
phase_radians = phase(sp).y

Arrays To Spectrum

re = [1, 0, 0, 0]
im = [0, 0, 0, 0]
sp = ({ __mathbookType: "spectrum", re: re, im: im, dx: 1, df: 1 / re.length, label: "manual spectrum" })
ifft(sp)

The most common way to make a spectrum is still fft(arrayOrSignal). Build a spectrum object manually only when you already have real and imaginary bins.

FFT And Spectra

fft() returns a spectrum with real and imaginary arrays plus frequency spacing. Power-of-two lengths use the fast path. Non-power-of-two lengths use a direct transform and are limited to 2048 samples.

FunctionWhat it doesExamples
fft(value)Transforms an array or signal into a spectrum.fft([1,0,0,0])
ifft(spectrum)Inverse FFT. Expects a spectrum from fft() and returns a signal.ifft(fft([1,2,3,4]))
fftshift(value)Circularly shifts an array, signal, or spectrum by half its length so the low-frequency center moves to the middle, MATLAB-style.fftshift([0,1,2,3]) -> [2,3,0,1]
mag(value)Magnitude of a spectrum. For arrays/signals, returns absolute values.mag(fft([1,0,0,0]))
phase(value)Phase angle of a spectrum in radians. For arrays/signals, returns 0 for non-negative values and pi for negative values.phase(fft([1,0,0,0]))
real(value)Real part of a spectrum. For arrays/signals, returns the numeric values.real(fft([1,2,3,4]))
imag(value)Imaginary part of a spectrum. For arrays/signals, returns zeroes.imag(fft([1,2,3,4]))
freqs(spectrum)Returns frequency bin values for a spectrum.freqs(fft(discrete(x => sin(x), 0, 10, 0.1)))

Plotting

The Plot button evaluates an expression over the current X range. Use X or x as the plotted variable.

sin(X)
sin(X) / X
exp(-X*X)

plot() lets an expression provide its own plot data instead of using the X range sampler.

FormWhat it doesExamples
plot(value)Plots an array, signal, spectrum, or an array of series. Arrays use indexes as X. Signals use x0 and dx. Spectra plot magnitude.plot([3,1,4,1,5])
plot([s.re, s.im])
plot(mag(fft(s)))
plot(xArray, yArray)Plots explicit X and Y arrays/signals. yArray may also be an array of series for multi-line plots.plot(range(0,5), [0,1,4,9,16])
plot(freqs(s), [real(sp), imag(sp)])

After plotting, PLOT contains the latest sampled plot points.

History And Special Values

NameMeaningExamples
_Most recent result._ * 2
__Second most recent result._ - __
___Third most recent result.___
INArray of executed input strings.IN[IN.length - 1]
OUTArray of output values.OUT[OUT.length - 1]
PLOTLatest plot point data collected by the plotting engine.PLOT.length
X, xThe current X value during plot evaluation. Available when plotting.sin(X)