Topic

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 ∑k=110k2\sum_{k=1}^{10} k^2.

The harmonic numbers Hn=∑k=1n1kH_n = \sum_{k=1}^n \frac1k are a good test of exactness: the denominator of HnH_n grows roughly like ene^n (it is close to lcm⁡(1,…,n)\operatorname{lcm}(1, \ldots, n)), 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.

∑i=110i2=385,∑i=141i=2512,∏j=15j=120. \sum_{i=1}^{10} i^2 = 385, \qquad \sum_{i=1}^{4} \frac1i = \frac{25}{12}, \qquad \prod_{j=1}^{5} j = 120.
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]
Try itEdit the code and run it with @ratmath/core in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs