Skip to content

Commit

Permalink
Make convergent calculator more sane
Browse files Browse the repository at this point in the history
  • Loading branch information
frostburn committed Dec 26, 2023
1 parent 22b15a3 commit e6e9e2c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
6 changes: 6 additions & 0 deletions src/__tests__/approximation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
22 changes: 13 additions & 9 deletions src/approximation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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!) {
Expand Down

0 comments on commit e6e9e2c

Please sign in to comment.