Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symbolic Array of Symbolic Size in SymPy

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 ...

like image 203
GPU Programmer Avatar asked Feb 03 '26 15:02

GPU Programmer


1 Answers

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))
like image 141
Aicody Avatar answered Feb 06 '26 05:02

Aicody



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!