Continued fractions and 355/113 in JavaScript
Advanced · 4 min read
People have used 22/7 for pi for two thousand years. A less famous fraction, 355/113, is far better: it is right to seven significant figures, 3.141592..., using only six digits. Where do fractions like these come from, and why are they so good? The answer is continued fractions, a way of writing any number as a list of whole numbers.
In this tutorial you will expand Math.PI into that list, turn the list back into the fractions 3, 22/7, 333/106 and 355/113, and check by brute force that no fraction with a denominator up to 1000 does better. Then you will run the same method backwards to turn the decimal 0.1 back into 1/10, and see a strange giant term that floating-point error sneaks into the list. You need to know loops, arrays and Math.floor.
A number as a list of whole numbers
Take 2.75. Its whole part is 2. What's left is 0.75. Flip it over: 1 / 0.75 = 1.333... Its whole part is 1, and 0.333... is left. Flip that: 1 / 0.333... = 3, and nothing is left.
The whole parts, [2, 1, 3], are the terms of the continued fraction. They mean 2 + 1 / (1 + 1 / 3), which is 2.75 again.
Convergents
If you stop the list early, you get a fraction close to the number. These fractions are called convergents. For pi, stopping after one term gives 3, after two gives 22/7, after four gives 355/113. Each one is the best fraction for its size.
Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.
110 Continued fractions, and why 355/113 is famous
hardExpand Math.PI as a continued fraction, build its convergents, and show that no fraction with a denominator under a thousand approximates pi better than 355/113. Then run the machine backwards to recover 1/10 from the double 0.1, and find the spurious term that float error injects into the expansion of an exact value like 2.75.
Stuck? Three hints, smallest first
- 1. Take the whole part, subtract it, invert what is left, repeat. The whole parts are the terms.
- 2. Convergents come from the terms by a two-line recurrence:
p = a * p + pPrevand the same forq. - 3. A brute-force search over every denominator up to 1000, taking
p = Math.round(x * q), settles the "best" claim without any theory.
Step 1: find the terms
function terms(x, count) {
const out = [];
let v = x;
for (let i = 0; i < count; i++) {
const a = Math.floor(v);
out.push(a);
const frac = v - a;
if (frac === 0) break;
v = 1 / frac;
}
return out;
}
console.log(terms(Math.PI, 12).join(' ')); // 3 7 15 1 292 1 1 1 2 1 3 1
This is the hand method in code: take the whole part, keep what's left, flip it, repeat. count limits how many terms you want, and the loop stops early if nothing is left.
Notice the 292. A big term means the fraction just before it is extra good. That is why 355/113, the convergent right before 292, is so accurate.
Step 2: build the convergents
Each convergent p / q comes from the two before it, using the next term a: the new top is a * p + pPrev, and the new bottom is a * q + qPrev.
function convergents(list) {
let pPrev = 1;
let p = list[0];
let qPrev = 0;
let q = 1;
const out = [[p, q]];
for (let i = 1; i < list.length; i++) {
const a = list[i];
const pNext = a * p + pPrev;
const qNext = a * q + qPrev;
pPrev = p;
p = pNext;
qPrev = q;
q = qNext;
out.push([p, q]);
}
return out;
}
const piConvergents = convergents(terms(Math.PI, 12)).slice(0, 5);
console.log(piConvergents.map(([p, q]) => p + '/' + q).join(' ')); // 3/1 22/7 333/106 355/113 103993/33102
The starting values, 1 and 0 for the "previous" fraction, are chosen so the recurrence works from the very first term. [p, q] in the arrow function pulls the two numbers out of each pair.
Step 3: how close is each one?
const errors = piConvergents.map(([p, q]) => p / q - Math.PI);
console.log(errors[1], errors[2], errors[3]); // 0.0012644892673496777 -0.0000832196275291075 2.667641894049666e-7
22/7 is high by about 0.0013. 333/106 is low. 355/113 is high again, by only 0.00000027. The errors switch sides every time, so the convergents close in on pi from both sides.
Step 4: check "best" by brute force
function bestFraction(x, maxQ) {
let best = [1, 1];
let bestError = Infinity;
for (let q = 1; q <= maxQ; q++) {
const p = Math.round(x * q);
const error = Math.abs(p / q - x);
if (error < bestError) {
bestError = error;
best = [p, q];
}
}
return best;
}
console.log(bestFraction(Math.PI, 100), bestFraction(Math.PI, 1000)); // [ 311, 99 ] [ 355, 113 ]
For each denominator q, the best top is Math.round(x * q). Try all of them and keep the closest. Up to 1000, nothing beats 355/113. No theory needed, just a loop.
Step 5: decimals back to fractions
The same machine can recover the fraction a person meant from a decimal:
function toFraction(x, tol) {
const list = terms(x, 40);
const all = convergents(list);
for (const [p, q] of all) {
if (Math.abs(p / q - x) <= tol) return [p, q];
}
return all[all.length - 1];
}
console.log(toFraction(0.1, 1e-12), toFraction(0.07, 1e-12)); // [ 1, 10 ] [ 7, 100 ]
console.log(3602879701896397 / 2 ** 55 === 0.1); // true
It walks through the convergents and returns the first one within the tolerance tol. The second line shows that the double 0.1 is really 3602879701896397 / 2 to the 55, not exactly a tenth. The continued fraction still finds 1/10, because 1 / 0.1 rounds to exactly 10.
Step 6: the wrong turn, trusting frac === 0
console.log(terms(2.75, 4)); // [ 2, 1, 3, 1125899906842624 ]
console.log(2 ** 50); // 1125899906842624
By hand, 2.75 is [2, 1, 3]. The code adds a fourth, enormous term. At the third step, 1 / 0.333... comes out as 3.000000000000001, so what's left is a tiny 8.9e-16 (2 to the -50) instead of 0. Flipping that gives 2 to the 50.
A huge term like this means precision has run out, not that the number is interesting. Real code should stop when what's left is tiny, not only when it is exactly zero.
Step 7: the golden ratio is all ones
const golden = convergents(terms((1 + Math.sqrt(5)) / 2, 10)).map(([p, q]) => p + '/' + q);
console.log(golden.join(' ')); // 1/1 2/1 3/2 5/3 8/5 13/8 21/13 34/21 55/34 89/55
The golden ratio's terms are all 1, the smallest possible, so its convergents improve as slowly as any number's can. They are ratios of neighboring Fibonacci numbers.
The full solution
The answer panel has terms, convergents, bestFraction and toFraction, and prints pi, 0.1, 0.07, the golden ratio, the square root of 2 and 2.75. Press Run to see the output.
// Terms: whole part, subtract, invert, repeat.
function terms(x, count) {
const out = [];
let v = x;
for (let i = 0; i < count; i++) {
const a = Math.floor(v);
out.push(a);
const frac = v - a;
if (frac === 0) break;
v = 1 / frac;
}
return out;
}
// Convergents: p / q, each built from the two before it.
function convergents(list) {
let pPrev = 1;
let p = list[0];
let qPrev = 0;
let q = 1;
const out = [[p, q]];
for (let i = 1; i < list.length; i++) {
const a = list[i];
const pNext = a * p + pPrev;
const qNext = a * q + qPrev;
pPrev = p;
p = pNext;
qPrev = q;
q = qNext;
out.push([p, q]);
}
return out;
}
// The best fraction with denominator at most maxQ, found by looking at all of them.
function bestFraction(x, maxQ) {
let best = [1, 1];
let bestError = Infinity;
for (let q = 1; q <= maxQ; q++) {
const p = Math.round(x * q);
const error = Math.abs(p / q - x);
if (error < bestError) {
bestError = error;
best = [p, q];
}
}
return best;
}
// Backwards: grow convergents until one is within tol of x.
function toFraction(x, tol) {
const list = terms(x, 40);
const all = convergents(list);
for (const [p, q] of all) {
if (Math.abs(p / q - x) <= tol) return [p, q];
}
return all[all.length - 1];
}
const piTerms = terms(Math.PI, 12);
const piConvergents = convergents(piTerms).slice(0, 5);
const errors = piConvergents.map(([p, q]) => p / q - Math.PI);
const golden = convergents(terms((1 + Math.sqrt(5)) / 2, 10)).map(([p, q]) => p + '/' + q);
const root2 = terms(Math.SQRT2, 8);
const exactValue = terms(2.75, 4);
console.log('pi terms :', piTerms);
console.log('convergents :', piConvergents.map(([p, q]) => p + '/' + q));
console.log('errors :', errors);
console.log('best q <= 100 :', bestFraction(Math.PI, 100));
console.log('best q <= 1000:', bestFraction(Math.PI, 1000));
console.log('0.1 back :', toFraction(0.1, 1e-12), 'and 0.07 gives', toFraction(0.07, 1e-12));
console.log('the double 0.1:', 3602879701896397, '/ 2 ** 55');
console.log('golden :', golden);
console.log('root 2 terms :', root2);
console.log('2.75 terms :', exactValue, '<- the last one is not real');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('pi expands as 3, 7, 15, 1, 292, then ones and twos', piTerms, [3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1]);
test('whose convergents are the famous approximations of pi', piConvergents, [[3, 1], [22, 7], [333, 106], [355, 113], [103993, 33102]]);
test('22/7 is high by 0.00126 and 355/113 by 2.7e-7, alternating sides', errors.slice(1, 4), [0.0012644892673496777, -0.0000832196275291075, 2.667641894049666e-7]);
test('and the fifth is out by only 5.8e-10, which is nine correct digits of pi', [errors[4], Math.abs(errors[4]) < 6e-10], [-5.778906242426274e-10, true]);
test('no denominator up to 1000 beats 355/113, though 99 gives only 311/99', [bestFraction(Math.PI, 1000), bestFraction(Math.PI, 100)], [[355, 113], [311, 99]]);
test('run backwards, the double 0.1 gives back one tenth, and 0.07 seven hundredths', [toFraction(0.1, 1e-12), toFraction(0.07, 1e-12)], [[1, 10], [7, 100]]);
test('even though that double is really 3602879701896397 over 2 ** 55', 3602879701896397 / 2 ** 55 === 0.1, true);
test('the golden ratio is all ones, so its convergents are ratios of Fibonacci numbers', golden, ['1/1', '2/1', '3/2', '5/3', '8/5', '13/8', '21/13', '34/21', '55/34', '89/55']);
test('and the expansion of 2.75 is [2, 1, 3] plus a spurious 2 ** 50 from float error', [exactValue, exactValue[3] === 2 ** 50], [[2, 1, 3, 1125899906842624], true]);
A continued fraction is the answer to "what is the best fraction for this number", and the convergents of pi are the answers people have been quoting for two thousand years: 3, 22/7, 333/106, 355/113. The brute-force search is there to make the claim concrete — of all 1000 denominators, none beats 113, and 355/113 is right to seven significant figures. That is why it survived: three digits over three digits, and better than you have any right to expect. Notice the errors alternate sign, which is a property of the expansion, not luck.
Backwards, the same recurrence turns a double into the fraction a human meant. toFraction(0.1) returns [1, 10], and it has to, because the expansion asks 1 / (0.1 - 0) and 1 / 0.1 is exactly 10 in doubles even though 0.1 is not exactly a tenth — the real value is 3602879701896397 / 255, as the seventh assertion shows. This is the honest way to display a computed ratio as a fraction, and it is worth more than toFixed when the answer is meant to be rational.
The last assertion is the trap. 2.75 is exactly representable and its expansion is exactly [2, 1, 3], three terms. What comes back is [2, 1, 3, 1125899906842624], because at the third step the remaining fraction is 4.4e-16 instead of 0, and inverting that gives 250. Any expansion loop needs a tolerance on the remainder rather than frac === 0, or a cap on the term size — an enormous term means you have run out of precision, not that the number is interesting.
Common mistakes
- Stopping only when the remainder is exactly 0. Float error leaves a tiny remainder and a giant fake term.
- Getting the starting values wrong. The recurrence needs
pPrev = 1, qPrev = 0before the first term. - Showing a ratio with
toFixed. If the answer is meant to be a fraction,toFractiongives 1/10 instead of 0.1000.
Try it yourself
- Expand
Math.SQRT2into terms. What pattern do you see after the first term? - Change
termsto stop whenfrac < 1e-9, and check that 2.75 gives[2, 1, 3]. - Use
toFractionon 0.333333 with a tolerance of 1e-5.