Last active
July 30, 2026 14:53
-
-
Save qntm/524ebf6de924395e9b07bdcefabeaf2e to your computer and use it in GitHub Desktop.
Compute base-10, base-2 and natural logarithms of JavaScript BigInts
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
| import Decimal from 'decimal.js' | |
| BigInt.log10 = x => Decimal.log(x, 10).toNumber() | |
| BigInt.log2 = x => Decimal.log(x, 2).toNumber() | |
| BigInt.log = x => Decimal.ln(x).toNumber() // `Decimal.log(x, Math.E)` gives incorrect results |
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
| /* | |
| This alternate implementation requires no third-party dependencies. | |
| However, due to the limitations of floating point, | |
| the results are sometimes slightly inaccurate. | |
| For example, `BigInt.log2(16n)` evaluates to `3.9999999999999996` | |
| */ | |
| const embiggen = logB => { | |
| const logB10 = logB(10) | |
| return x => { | |
| if (typeof x !== 'bigint' || x < 0n) { | |
| return NaN | |
| } | |
| const s = x.toString(10) | |
| return logB(Number.parseFloat(`0.${s}`)) + s.length * logB10 | |
| } | |
| } | |
| BigInt.log10 = embiggen(Math.log10) | |
| BigInt.log2 = embiggen(Math.log2) | |
| BigInt.log = embiggen(Math.log) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: