Skip to content
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

multinomial() may lead to hidden overflow #99

Open
sylvaticus opened this issue Sep 23, 2020 · 2 comments · May be fixed by #172
Open

multinomial() may lead to hidden overflow #99

sylvaticus opened this issue Sep 23, 2020 · 2 comments · May be fixed by #172
Labels

Comments

@sylvaticus
Copy link

multinomial internally uses binomial. While the latter check for overflow, the whole computation of multinomial is not checked for overflow, leading to :

multinomial(150, 150, 150, 150) --> error overflow reported by binomial
multinomial(15, 15, 15, 15) --> no error reported

See also this thread on Discourse.

@GoodDayToYouAll
Copy link

Since this has been dormant for a while and I ran into this exact problem, I wanted to give this issue a small kick:

I would say that multinomial(15,15,15) returning a negative value is very dangerous and can lead to very hard to detect bugs.

@inkydragon
Copy link
Member

inkydragon commented Nov 27, 2024

A quick fix that detects the overflow properly:

function multinomial(k...)
    s = 0
    result = 1
    @inbounds for i in k
        s += i
        bi = binomial(s, i)
        result, f = Base.mul_with_overflow(result, bi)
        f && error("overflow: $(result)")
    end
    result
end
julia> multinomial(15, 15, 15, 15)
ERROR: overflow: -1845252435754023168
Stacktrace:

Need to further examine the performance cost and see if we need to put the error path outside of the for loop, and then we can send the pr.

@inkydragon inkydragon added the bug label Nov 27, 2024
@inkydragon inkydragon linked a pull request Dec 13, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants