16

I am using Symbolics.jl and I want to make a mathematical summation, equivalent to the function Sum from Sympy (https://docs.sympy.org/latest/modules/concrete.html)

The documentation of Symbolics.jl suggests that it is possible:

  • Discrete math (representations of summations, products, binomial coefficients, etc.)

However, in the frequently asked questions, the opposite is suggested:

Loops are allowed, but the amount of loop iterations should not require that you know the value of the symbol x.

2 Answers 2

17

You can use +(x...) for a summation for a vector of symbols.

julia> @variables x[1:5]
1-element Vector{Symbolics.Arr{Num, 1}}:
 x[1:5]

julia> +(x...)
x[1] + x[2] + x[3] + x[4] + x[5]

julia> Symbolics.derivative(+(x...), x[2])
1

Beware of sum(x) as it seems to be not expanded and yields incorrect results:

julia> sum(x)
Symbolics._mapreduce(identity, +, x, Colon(), (:init => false,))

julia> Symbolics.derivative(sum(x), x[2])
0

Last but not least, make another step and define the summation symbol to get a nice experience:

julia> ∑(v) = +(v...)
∑ (generic function with 1 method)

julia> ∑(x)
x[1] + x[2] + x[3] + x[4] + x[5]

julia> Symbolics.derivative(100∑(x), x[2])
100
Sign up to request clarification or add additional context in comments.

Comments

12

It extends Julia itself, so there really isn't much to document: just use Julia on the symbolic values. Thus here, just use sum, which is part of Base Julia.

julia> using Symbolics

julia> @variables x[1:5]
1-element Vector{Symbolics.Arr{Num, 1}}:
 x[1:5]

julia> x = collect(x)
5-element Vector{Num}:
 x[1]
 x[2]
 x[3]
 x[4]
 x[5]

julia> sum(x)
x[1] + x[2] + x[3] + x[4] + x[5]

"Loops are allowed, but the amount of loop iterations should not require that you know the value of the symbol x."

That's also a limitation of SymPy, or any other symbolic tracing system because that restricts to symbolically-reprsentable (quasi-static) codes. This is discussed in more depth in this blog post.

2 Comments

why am I getting Symbolics._mapreduce(identity, +, x, Colon(), (:init => false,)) when trying to do sum(x). Now I know I can do sum(collect(x)) but this looks kind of weird.
It's converting from a Symbolic Array to an array of Symbols. The Symbolic Array keeps the operation lazy (though with a nasty way of printing it, that IMO is worth an issue) so it has an O(1) representation of the operation. collect(x) gives an array of scalar symbols which it then calls sum on. That's an O(n) representation, like SymPy. Symbolic Arrays are just not a completed functionality at this point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.