I am new to sympy and I want to calculate the derivative of a finite series with variables in two periods. For example, I tried the following code:
from sympy import symbols, Sum, diff, IndexedBase, Idx
T = symbols('T', interger=True)
t = symbols('t', interger=True)
β, σ = symbols('β σ')
a = symbols('a', cls=IndexedBase)
L = Sum(β * a[t] + σ * a[t + 1], (t, 0, T))
print(diff(L, a[t]))
I got the results like Sum(β, (t, 0, T))
. But in fact, my expectation is β+σ. Why? Because a[t] appears two times in this series. One is β * a[t] (when time=t) and another is σ * a[t] (when time=t-1).
How could I get the expected result with sympy? Thanks
In the context of a sum the summation variable is a bound dummy variable i.e. the Sum as a whole is not really a function of t
just like Integral(x, (x, 0, 1)) = 1/2
is not really a function of x
. It does not make sense to use the same symbol t
outside of the sum when it is not free in L
.
Instead use a different symbol:
In [25]: L
Out[25]:
T
___
╲
╲
╱ (β⋅a[t] + σ⋅a[t + 1])
╱
‾‾‾
t = 0
In [26]: L.diff(a[n])
Out[26]:
T
___
╲
╲ ⎛β⋅δ + σ⋅δ ⎞
╱ ⎝ n,t n,t + 1⎠
╱
‾‾‾
t = 0
In [27]: L.diff(a[n]).doit()
Out[27]:
⎧β + σ for T ≥ n ∧ T ≥ n - 1 ∧ n ≥ 0 ∧ n ≥ 1
⎪
⎪ β for T ≥ n ∧ n ≥ 0
⎨
⎪ σ for T ≥ n - 1 ∧ n ≥ 1
⎪
⎩ 0 otherwise