Consider taking the (symbolic) derivative of sum of a function applied to each element of a data set. The conceptual code would be something like:
a = Symbol('a')
n = Symbol('n')
k = symbol('k')
cost = sum(a*data[k] + k, (k,0,n-1))
diff(cost, a)
I'd like it to produce a symbolic result:
sum(data[k], (k,0,n-1))
My core problem is how to specify data to be an array of size that is specified by the symbol n.
I tried to use a funciton, but that invokes the chain rule.
I used an array of specified size, that worked, but generates an expanded result (not useful in n = 1_000).
The real problem involves complex functions that don't trivially decompose ...
You can use IndexedBase() and Sum() to symbolically generate the derivative (using diff()):
import sympy as sp
a, n, k = sp.symbols("a n k")
data = sp.IndexedBase("data")
cost = sp.Sum(a * data[k] + k, (k, 0, n - 1))
res = sp.diff(cost, a).doit()
>>> print(res)
Sum(data[k], (k, 0, n - 1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With