Skip to content

Commit

Permalink
Make fraction defloating strategy more robust
Browse files Browse the repository at this point in the history
  • Loading branch information
frostburn committed Jan 17, 2024
1 parent e2087e1 commit 5d6574c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
6 changes: 6 additions & 0 deletions src/__tests__/fraction.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,4 +227,10 @@ describe('Fraction', () => {
'Numerator above safe limit'
);
});

it('can convert a problematic float to a fraction', () => {
const x = 0.5717619047619048;
const y = new Fraction(x);
expect(y.valueOf()).toBeCloseTo(x);
});
});
19 changes: 13 additions & 6 deletions src/fraction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,13 +250,20 @@ export class Fraction {
if (!coefs.length) {
throw new Error('Numerator above safe limit');
}
let n = coefs.pop()!;
let d = 1;
while (coefs.length) {
[n, d] = [d + n * coefs.pop()!, n];
let j = 1;
while (j <= coefs.length) {
let n = coefs[coefs.length - j];
let d = 1;
for (let i = coefs.length - j - 1; i >= 0; --i) {
[n, d] = [d + n * coefs[i], n];
}
this.n = n;
this.d = d;
if (n <= Number.MAX_SAFE_INTEGER && d <= Number.MAX_SAFE_INTEGER) {
break;
}
j++;
}
this.n = n;
this.d = d;
}
this.reduce();
}
Expand Down

0 comments on commit 5d6574c

Please sign in to comment.