CedEvolModelo
CedEvolModelo

Reputation: 161

With Julia Symbolics, how can I do a mathematical summation?

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.

Upvotes: 16

Views: 2464

Answers (2)

Chris Rackauckas
Chris Rackauckas

Reputation: 19162

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.

Upvotes: 12

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42264

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

Upvotes: 17

Related Questions