SymPy:如何实现索引系数乘以索引函数的求和?
更新:
我想运行一个generate_function(3),例如得到以下输出:
c_0 * F(0) + c_1 * F(1) + c_2 * F(2) + c_3 * F(3)
其中 c_i 只是一个符号,而 F(i) 是一个函数或一个对象,我稍后可以将其用于其余代码。
我只是想使用 SymPy 来实现求和:
求和(从 i = 0 到 n)c_i * f(i)
其中 c_i 是索引常量(符号),f 是参数为 i 的函数。
我尝试了很多次,但都失败了。
def generate(n):
coeff = sym.symbols('c0:{}'.format(n))
def f(i):
return i
return sym.Sum(coeff(i) * f(i),(i,0,n))
我得到:“元组”对象不可调用
感谢您的帮助
Update:
I want to run a generate_function(3) for example to have an output of:
c_0 * F(0) + c_1 * F(1) + c_2 * F(2) + c_3 * F(3)
where c_i is just a symbol, while F(i) is a function or an object that I can use later for the rest of code.
I simply want to use SymPy to implement the summation:
summation (from i = 0 to n) c_i * f(i)
where c_i is indexed constant (symbol) and f is a function with argument of i.
I tried many times and failed.
def generate(n):
coeff = sym.symbols('c0:{}'.format(n))
def f(i):
return i
return sym.Sum(coeff(i) * f(i),(i,0,n))
I got: 'tuple' object is not callable
Thanks for help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
目前还不完全清楚你想要什么,但也许就是这样:
It's not completely clear what you want but maybe this is it:
您创建了一个符号元组:
将这样的元组视为一个函数(如
f(i)
中所示)是行不通的。这就是基本的Python!虽然索引对于创建许多符号来说是一个很好的简短,但结果与执行symbols('xy z')
没有什么不同您可以索引元组
您可以使用列表理解来创建表达式列表:
甚至应用基本
sum
函数来创建sympy.Add
表达式:You created a tuple of symbols:
Treating such a tuple as though it were a function, as in
f(i)
, does not work. That's basic Python! While the indexing is a nice short to making many symbols, the result is no different from doingsymbols('x y z')
You can index the tuple
You could use a list comprehension to make a list of expressions:
and even apply the base
sum
function to create asympy.Add
expression: