Lists, sums and products
range, seq, sum and product build and total lists of exact values. They are what the RatCalc calculator uses for sums like .
The harmonic numbers are a good test of exactness: the denominator of grows roughly like (it is close to ), so a float sum keeps only 16 of its digits while sum keeps all of them.
range
range(start, end, step = 1) is inclusive at both ends. Arguments are anything R interpolation accepts, so steps can be fractions. A negative step counts down; a zero step throws, as does a list longer than a million values.
import { R, range, seq, sum, product } from "@ratmath/core";
range(1, 5); // [1, 2, 3, 4, 5]
range(0, 1, R`1/4`); // [0, 1/4, 1/2, 3/4, 1]
range(5, 1, -2); // [5, 3, 1]
seq, sum, product
Each takes a list, or start, end[, step] as for range, and an optional function (value, index) => term. sum and product add or multiply exactly; empty input gives 0 and 1.
seq(0, 6, 2, (k) => R`${k}^3`); // [0, 8, 64, 216]
sum(1, 10, (i) => R`${i}^2`); // 385
sum(1, 4, (i) => R`1/${i}`); // 25/12
product(1, 5, (j) => j); // 120
sum([R`1:2`, 1]); // 2:3, intervals add too
ExactList
range and seq return an ExactList, an Array subclass: indexing, spread, map and filter all work. Its own methods never change the list: sum, product, elementwise add, subtract, multiply, divide (by a constant or a list of the same length), pow(n), min, max. exact(values) converts any iterable.
const xs = range(1, 4);
xs.multiply(R`1/2`).product(); // 3/2
xs.pow(-1).sum(); // 25/12
xs.add(range(4, 1, -1)); // [5, 5, 5, 5]
@ratmath/core in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.