Reputation: 533
I have recently been trying to learn how to use symbolic calculus in Python. Most of the basic SymPy tutorials were easy enough, but how would I go about representing something as complex as the N-dimensional (for even N) Rosenbrock function? This function has two main complicating factors: its argument is a vector and the function accesses specific, indexed elements in this vector, and the function includes an indexed sum.
Is it possible to represent something like this in SymPy? If so, could you provide a code snippet or tips on how I could handle these two challenges?
Upvotes: 0
Views: 340
Reputation: 14500
You can do this using Sum
and Indexed
:
https://docs.sympy.org/latest/modules/concrete.html
https://docs.sympy.org/latest/modules/tensor/indexed.html
In [34]: x = IndexedBase('x')
In [35]: i, n = symbols('i, n', integer=True)
In [36]: Sn = Sum(100*(x[2*i-1]**2 - x[2*i])**2 + (x[2*i-1] - 1)**2, (i, 1, n))
In [37]: Sn
Out[37]:
n
____
╲
╲
╲ ⎛ 2⎞
╱ ⎜ 2 ⎛ 2 ⎞ ⎟
╱ ⎝(x[2*i - 1] - 1) + 100⋅⎝x[2*i - 1] - x[2*i]⎠ ⎠
╱
‾‾‾‾
i = 1
In [38]: Sn.subs(n, 2).doit()
Out[38]:
2 2
2 ⎛ 2 ⎞ 2 ⎛ 2 ⎞
(x[1] - 1) + 100⋅⎝x[1] - x[2]⎠ + (x[3] - 1) + 100⋅⎝x[3] - x[4]⎠
You can do things with Sn
but there are limitations on what operations you can use without replacing n
with a concrete integer.
Upvotes: 1