-
-
Notifications
You must be signed in to change notification settings - Fork 441
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
update efficiency of calculating binomial coefficients #2442
Comments
👋 Hi there! 👋 And thank you for opening your first issue! We will get back to you shortly. 🏃 💨 |
@blazeshomida Thanks for opening this issue. The main concern I have for your proposed implementation is precision loss. Especially for large |
@kgryte So I've just done some simple testing in codesandbox, and I see your point with precision loss because of the use of logarithms. However, with a slight revision, you can achieve a result closer to what you're currently using, although I have seen slight differences near the end with very large numbers. This approach sacrifices a bit of precision when reaching large numbers, but any result smaller than that is accurate. It's not so much an update to make it better, just a slightly different approach, trading off precision for efficiency. function binomialCoefficient(n: number, k: number) {
if (k > n) return 0;
if (k === 0 || k === n) return 1;
if (n - k < k) k = n - k;
let result = 1;
for (let i = 0; i < k; i++) {
result *= (n - i) / (i + 1);
}
// Precision check
if (Math.abs(result - Math.round(result)) > Number.EPSILON) {
console.warn("Result may suffer from precision loss.");
}
return result;
} This function leverages symmetry and calculates only necessary values up to If you want to close this issue, feel free. After digging into it a bit more I understand the reasonings for the route you chose. |
Some related discussion: #1155. There may be an opportunity for adding a "fast" and less accurate version to |
I can make a formal PR/Issue, but just sitting on my phone talking with chatGPT trying to figure out how to efficiently calculate binomial coefficients,I was looking at how you solve binomial coefficients in this package; @stdlib/math-base-special-binomcoef, and was wondering if a solution such as this would be better?
This basically breaks it down to it's most simplest form (with log for maintaining precision) by stopping the loop once we reach k, so only calculating necessary values. Basically O(k) time complexity and O(1) space complexity.
Obviously error handling would need to be added but in a nutshell this is what I was thinking.
The text was updated successfully, but these errors were encountered: