Created
June 2, 2020 13:13
-
-
Save willfrew/4d805b4a7bf18ef0e82b3680e7831a87 to your computer and use it in GitHub Desktop.
Some fun with arbitrary base numbers (with specific tests for base PI)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe('convert number to arbitrary base-system coefficients', () => { | |
const truncateToFixed = (num: number, maxFractionalDigits: number): number => { | |
const multiplier = Math.pow(10, maxFractionalDigits); | |
return Math.floor(num * multiplier) / multiplier; | |
} | |
const toBaseCoefficients = (num: number, base: number): (number | '.')[] => { | |
const maxFractionalDigits = 10; | |
let coefficients = []; | |
let i = Math.ceil(Math.log(num) / Math.log(base)); | |
while ( | |
i >= 0 || | |
(i >= -1 * maxFractionalDigits && truncateToFixed(num, maxFractionalDigits) !== 0) | |
) { | |
if (i === -1) { | |
coefficients.push('.'); | |
} | |
const base_i = Math.pow(base, i); | |
const a_i = Math.floor(num / base_i); | |
num = num - (a_i * base_i); | |
if (!(coefficients.length === 0 && a_i === 0)) { | |
// Don't push leading zeroes | |
coefficients.push(a_i); | |
} | |
i--; | |
} | |
return coefficients; | |
}; | |
it('should convert 0 base 10 to 0 base 2', () => { | |
expect(toBaseCoefficients(0, 2)).toEqual([]); | |
}); | |
it('should convert 10 base 10 to 1010 base 2', () => { | |
expect(toBaseCoefficients(10, 2)).toEqual([ 1, 0, 1, 0 ]); | |
}); | |
it('should convert 10 base 10 to A base 16', () => { | |
expect(toBaseCoefficients(10, 16)).toEqual([ 10 ]); | |
}); | |
it('should do something with base pi', () => { | |
expect(toBaseCoefficients(2 * Math.PI, Math.PI)).toEqual([ 2, 0 ]); | |
}); | |
it('should do something else with base pi', () => { | |
expect(toBaseCoefficients(10, Math.PI)).toEqual([ 1, 0, 0, '.', 0, 1, 0, 2, 2, 1, 2, 2, 2, 2 ]); | |
}); | |
it('should handle fractions', () => { | |
expect(toBaseCoefficients(1.12345, 10)).toEqual([ 1, '.', 1, 2, 3, 4, 5 ]); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment