ASKSAGE: Sage Q&A Forum - Individual question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Fri, 18 Dec 2015 08:04:35 -0600Symbolic function that sums over variable sequencehttp://ask.sagemath.org/question/31674/symbolic-function-that-sums-over-variable-sequence/How do I define a symbolic function that takes a sum of variables as value?
I have tried the following:
k=var('k')
f(x)=sum(x[k], k, 1, 5)
But I get the following error:
TypeError: unable to convert k to an integer
I want to be able to symbolically differentiate `f` with regards to e.g. `x[3]`.Fri, 18 Dec 2015 04:16:12 -0600http://ask.sagemath.org/question/31674/symbolic-function-that-sums-over-variable-sequence/Answer by tmonteil for <p>How do I define a symbolic function that takes a sum of variables as value?</p>
<p>I have tried the following:</p>
<pre><code>k=var('k')
f(x)=sum(x[k], k, 1, 5)
</code></pre>
<p>But I get the following error:</p>
<pre><code>TypeError: unable to convert k to an integer
</code></pre>
<p>I want to be able to symbolically differentiate <code>f</code> with regards to e.g. <code>x[3]</code>.</p>
http://ask.sagemath.org/question/31674/symbolic-function-that-sums-over-variable-sequence/?answer=31680#post-id-31680I am not sure to understand your question.
You can define a Python function that sums all elements of a list as follows:
sage: f = lambda x : sum(x)
sage: x = [1,2,3]
sage: f(x)
6
If you want to create some symbolic variables `x_i` in a list `x` and, at the same time inject them into the namespace (i.e. make them Python variables), you can do:
sage: x = [var("x_{}".format(i)) for i in range(5)]
sage: x
[x_0, x_1, x_2, x_3, x_4]
Then you can define their sum and differentiate according to some variable:
sage: f(x)
x_0 + x_1 + x_2 + x_3 + x_4
sage: f(x).diff(x_2)
1
Fri, 18 Dec 2015 08:04:35 -0600http://ask.sagemath.org/question/31674/symbolic-function-that-sums-over-variable-sequence/?answer=31680#post-id-31680