Published
Edited
Jun 6, 2022
3 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
// very slow but uses 200-digit decimal arithmetic
precise_tangent = (a, b) => {
let [ax, ay] = Dec(a), [bx, by] = Dec(b);
let {mul, add, sub, div} = Dec;
return +div(
sub(mul(ax, by), mul(ay, bx)),
add(mul(ax, bx), mul(ay, by))
)
}
Insert cell
naive_tangent = ([ax, ay], [bx, by]) =>
(ax*by - ay*bx) /
(ax*bx + ay*by)
Insert cell
careful_tangent = ([ax, ay], [bx, by]) =>
((ax + bx)*(by - ay) - (ay + by)*(bx - ax)) /
((ax - by)*(bx - ay) + (ay + bx)*(by + ax))
Insert cell
trig_tangent = ([ax, ay], [bx, by]) =>
Math.tan(Math.atan2(by, bx) - Math.atan2(ay, ax))
Insert cell
normalize = ([x, y]) =>
[x/Math.hypot(x, y), y/Math.hypot(x, y)]
Insert cell
eps = 2**-52
Insert cell
u1 = normalize([Math.PI, Math.E])
Insert cell
u2 = normalize([Math.PI+2*eps, Math.E])
Insert cell
precise_tangent(u1, u2)
Insert cell
naive_tangent(u1, u2)
Insert cell
careful_tangent(u1, u2)
Insert cell
trig_tangent(u1, u2)
Insert cell
(naive_tangent(u1, u2) - precise_tangent(u1, u2)) / precise_tangent(u1, u2) // relative error
Insert cell
(careful_tangent(u1, u2) - precise_tangent(u1, u2)) / precise_tangent(u1, u2) // relative error
Insert cell
(trig_tangent(u1, u2) - precise_tangent(u1, u2)) / precise_tangent(u1, u2) // relative error
Insert cell
u3 = [Math.cos(1.2), Math.sin(1.2)]
Insert cell
u4 = [Math.cos(1.2 - Math.PI/2), Math.sin(1.2 - Math.PI/2)]
Insert cell
naive_tangent(u3, u4)
Insert cell
careful_tangent(u3, u4)
Insert cell
precise_tangent(u3, u4)
Insert cell
trig_tangent(u3, u4)
Insert cell
(naive_tangent(u3, u4) - precise_tangent(u3, u4)) / precise_tangent(u3, u4) // relative error
Insert cell
(careful_tangent(u3, u4) - precise_tangent(u3, u4)) / precise_tangent(u3, u4) // relative error
Insert cell
(trig_tangent(u3, u4) - precise_tangent(u3, u4)) / precise_tangent(u3, u4) // relative error
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more