This site is version 0.0.1. Most of the code on this site is drafted by an agent and needs review. I apologize
for the AI-speak, we are working on rewriting it!
Classic numerical algorithms, each a few lines long. Run a cell to see its output beside the expected one.
Newton's square root
Repeat x = (x + a/x) / 2; each step roughly doubles the number of correct digits.
Viv [1]
defnewton_sqrt(a) {
x = a
for i to20 {
x =0.5* (x + a / x)
}
return x
}
shownewton_sqrt(2.0)
showsqrt(2.0)
Bisection
Root of cos(x) on [1, 2]. Each step halves the interval, so 40 halvings leave it 2^-40 ≈ 9e-13 wide and give pi/2 to about twelve digits; show prints the first six.
Viv [2]
defbisect_cos(lo, hi) {
for i to40 {
mid =0.5* (lo + hi)
ifcos(lo) *cos(mid) <0.0 {
hi = mid
} else {
lo = mid
}
}
return0.5* (lo + hi)
}
showbisect_cos(1.0, 2.0)
gcd via mod
Euclid's algorithm. The floats hold whole numbers exactly, so mod is exact.
Viv [3]
defgcd(a, b) {
if b <0.5 {
return a
}
returngcd(b, mod(a, b))
}
showgcd(1071.0, 462.0)
Horner evaluation
A polynomial as an array of coefficients, highest power first.
The dominant eigenvalue of a symmetric 2x2, found by repeated matrix-vector products; compare eig_sym.
Viv [5]
defnormalize(v) {
n =sqrt(v[0] * v[0] + v[1] * v[1])
return v / n
}
defrayleigh(A, v) {
w = A @ v
return v[0] * w[0] + v[1] * w[1]
}
A = [[2.0, 1.0], [1.0, 3.0]]
v = [1.0, 0.0]
for i to30 {
v =normalize(A @ v)
}
showrayleigh(A, v)
Compensated summation
Kahan's method carries each addition's rounding error into the next one. Adding 0.1 a million times this way gives exactly 100000.
Viv [6]
defkahan_sum(n, val) {
s =0.0
comp =0.0for i to n {
y = val - comp
t = s + y
comp = (t - s) - y
s = t
}
return s
}
showkahan_sum(1000000.0, 0.1) -100000.0
Fibonacci two ways
Naive recursion, whose number of calls grows exponentially with n, against a loop that takes n steps.
Viv [7]
deffib_rec(n) {
if n <1.5 {
return n
}
returnfib_rec(n -1.0) +fib_rec(n -2.0)
}
deffib_loop(n) {
a =0.0
b =1.0for i to n {
t = a + b
a = b
b = t
}
return a
}
showfib_rec(15.0)
showfib_loop(15.0)