Rational functions
Fractions of polynomials form a field, just as fractions of whole numbers do. Because it is a field, everything linear algebra does with numbers it can do with formulas.
The field of fractions
A rational function is a fraction of polynomials with , where and are the same when . With
they form a field, written : the smallest field containing the polynomial ring, in the same way Q is built from the integers.
A fraction has many names, so the library keeps each one in a single standard form. The numerator and denominator are divided by their gcd (lowest terms); over Q both then get whole-number coefficients with no common factor and the denominator's leading coefficient is made positive. Two rational functions are equal exactly when their standard forms match, which is what makes "is this expression zero?" a question with a definite answer.
import { ring, fractions } from "@ratmath/structures";
const R = ring("x, y");
const F = fractions(R); // the field Q(x, y)
const a = F.parse("1/(x + y)");
const b = F.parse("1/(x - y)");
String(a.add(b)); // "2x/(x² − y²)"
String(a.div(b)); // "(x − y)/(x + y)"
String(F.parse("(x^2 - y^2)/(x - y)")); // "x + y"
a.add(b).num; a.add(b).den; // the two polynomials
a.diff("x"); // −1/(x² + 2xy + y²) (the quotient rule)
a.subs({ y: 1 }); // 1/(x + 1)
a.at({ x: 2, y: 1 }); // Rational 1/3
A field object
fractions(R) is also a field object: it carries zero, one, add, sub, mul, div, neg and sign, the shape every RatMath library uses to say "do arithmetic here". Anything written against that shape works with formulas. In particular the elimination, determinant and inverse of @ratmath/linalg's field module accept it, which gives exact linear algebra with symbolic parameters:
import { field } from "@ratmath/linalg";
import { ring, fractions } from "@ratmath/structures";
const F = fractions(ring("a, b, c, d"));
const [a, b, c, d] = F.gens;
field.det([[a, b], [c, d]], F); // −bc + ad
field.inverse([[a, b], [c, d]], F); // [[−d/(bc − ad), b/(bc − ad)], [c/(bc − ad), −a/(bc − ad)]]
const G = fractions(ring("t"));
field.rref([[1, G.parse("t"), 1], [G.parse("t"), 1, 1]], G);
// x = 1/(t + 1), y = 1/(t + 1): the solution of the system as a formula in t
One caution comes with formulas: a result such as is correct as a rational function, and says nothing about the special value , where the original system has no solution. Elimination over the field treats any nonzero polynomial as a legitimate pivot.
Why the gcd matters
Without reduction to lowest terms, fractions grow without bound: adding fractions multiplies denominators together. Each operation here ends with one gcd, and sums are formed over the least common denominator, so the answer is as small as it can be.
@ratmath/structures and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.