Symbolics: get the coefficients of the polynomial binomial(x, c)

Oh right, this generalization. Yes, this is a indeed a polynomial for integer k. Right now, however, Julia only defines the binomial function for integers:

julia> methods(binomial)
# 3 methods for generic function "binomial":
[1] binomial(n::BigInt, k::UInt64) in Base.GMP at gmp.jl:684
[2] binomial(n::BigInt, k::Integer) in Base.GMP at gmp.jl:685
[3] binomial(n::T, k::T) where T<:Integer in Base at intfuncs.jl:1050

Arguably, it should have a method binomial(x::Number, k::Integer) (binomial(x,k) for non-integer x by stevengj · Pull Request #48124 · JuliaLang/julia · GitHub). If we add such a method:

function binomial(x::Number, k::Integer)
    k < 0 && throw(DomainError("k=$k must be non-negative"))
    k == 0 && return oneunit(x)/one(k)
    # we don't use prod(i -> (x-i+1), 1:k) / factorial(k),
    # and instead divide each term by i, to avoid spurious overflow.
    return prod(i -> (x-i+1)/i, OneTo(k))
end

along with a method Base.binomial(x::Num, k::Integer) = invoke(binomial, Tuple{Number, Integer}, x, k) to eliminate a method ambiguity in Symbolics.jl, then it works:

julia> binomial(x, 3)
x*((1//3)*x - (2//3))*((1//2)*x - (1//2))
2 Likes