From e6e9e2cdce04a08ada4881d53b634fbaf8fa1f0c Mon Sep 17 00:00:00 2001 From: Lumi Pakkanen Date: Tue, 26 Dec 2023 21:37:48 +0200 Subject: [PATCH] Make convergent calculator more sane --- src/__tests__/approximation.spec.ts | 6 ++++++ src/approximation.ts | 22 +++++++++++++--------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/__tests__/approximation.spec.ts b/src/__tests__/approximation.spec.ts index 1d4669f..c3e6a4c 100644 --- a/src/__tests__/approximation.spec.ts +++ b/src/__tests__/approximation.spec.ts @@ -120,6 +120,12 @@ describe('Convergent calculator', () => { expect(semiconvergents[3].equals('10/3')).toBeTruthy(); expect(semiconvergents[4].equals('13/4')).toBeTruthy(); }); + + it('calculates convergents for 1\\5', () => { + expect(() => + getConvergents(1.148698354997035, undefined, 256, true, false) + ).not.toThrow(); + }); }); describe('Radical approximator', () => { diff --git a/src/approximation.ts b/src/approximation.ts index b37970e..a9737f4 100644 --- a/src/approximation.ts +++ b/src/approximation.ts @@ -52,17 +52,21 @@ export function getConvergents( if (includeNonMonotonic) { result.push(convergent); } else { - // See https://en.wikipedia.org/wiki/Continued_fraction#Semiconvergents - // for the origin of this half-rule if (2 * i > cfDigit) { result.push(convergent); - } else if ( - convergent - .sub(value_) - .abs() - .compare(result[result.length - 1].sub(value_).abs()) < 0 - ) { - result.push(convergent); + } else { + // See https://en.wikipedia.org/wiki/Continued_fraction#Semiconvergents + // for the origin of this half-rule + try { + const halfRule = + convergent + .sub(value_) + .abs() + .compare(result[result.length - 1].sub(value_).abs()) < 0; + if (halfRule) { + result.push(convergent); + } + } catch {} } } if (result.length >= maxLength!) {