如何在SymPy中生成给定维的符号多元多项式? [英] How to generate a symbolic multivariate polynomial of a given dimension in SymPy?

查看:225
本文介绍了如何在SymPy中生成给定维的符号多元多项式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用幂级数来近似一些PDE.给定一个numpy ndarray,我首先需要生成符号多元多项式.

I want to use power series to approximate some PDEs. The first step I need to generate symbolic multivariate polynomials, given a numpy ndarray.

考虑以下多项式:

我想采用D=[d1,...,dm]mndarray,其中dj是非负整数,并以符号表达式的形式生成符号多元多项式.符号表达式由以下形式的单项式组成:

I want to take a m dimensional ndarray of D=[d1,...,dm] where djs are non-negative integers, and generate a symbolic multivariate polynomial in the form of symbolic expression. The symbolic expression consists of monomials of the form:

例如,如果D=[2,3]输出应为

对于这种特定情况,我可以嵌套两个for loops并添加表达式.但是我不知道该怎么处理任意长度的D.如果可以在不使用for循环的情况下生成AXD维ndarray,则可以将np.sum(np.multiply(A,X))用作 Frobenius内部产品可以满足我的需求.

For this specific case I could nest two for loops and add the expressions. But I don't know what to do for Ds with arbitrary length. If I could generate the D dimensional ndarrays of A and X without using for loops, then I could use np.sum(np.multiply(A,X)) as Frobenius inner product to get what I need.

推荐答案

我会使用

I would use symarray and itertools.product for this:

from sympy import *
import itertools
D = (3, 4, 2, 3)
a = symarray("a", D)
x = symarray("x", len(D))
prod_iterator = itertools.product(*map(range, D))
result = Add(*[a[p]*Mul(*[v**d for v, d in zip(x, p)]) for p in prod_iterator])

结果是

a_0_0_0_0 + a_0_0_0_1*x_3 + a_0_0_0_2*x_3**2 + a_0_0_1_0*x_2 + a_0_0_1_1*x_2*x_3 + a_0_0_1_2*x_2*x_3**2 + a_0_1_0_0*x_1 + a_0_1_0_1*x_1*x_3 + a_0_1_0_2*x_1*x_3**2 + a_0_1_1_0*x_1*x_2 + a_0_1_1_1*x_1*x_2*x_3 + a_0_1_1_2*x_1*x_2*x_3**2 + a_0_2_0_0*x_1**2 + a_0_2_0_1*x_1**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**2 + a_2_1_1_0*x_0**2*x_1*x_2 + a_2_1_1_1*x_0**2*x_1*x_2*x_3 + a_2_1_1_2*x_0**2*x_1*x_2*x_3**2 + a_2_2_0_0*x_0**2*x_1**2 + a_2_2_0_1*x_0**2*x_1**2*x_3 + a_2_2_0_2*x_0**2*x_1**2*x_3**2 + a_2_2_1_0*x_0**2*x_1**2*x_2 + a_2_2_1_1*x_0**2*x_1**2*x_2*x_3 + a_2_2_1_2*x_0**2*x_1**2*x_2*x_3**2 + a_2_3_0_0*x_0**2*x_1**3 + a_2_3_0_1*x_0**2*x_1**3*x_3 + a_2_3_0_2*x_0**2*x_1**3*x_3**2 + a_2_3_1_0*x_0**2*x_1**3*x_2 + a_2_3_1_1*x_0**2*x_1**3*x_2*x_3 + a_2_3_1_2*x_0**2*x_1**3*x_2*x_3**2

备注:

  1. symarray取决于NumPy,但这对您来说似乎不是问题.如果是这样,我将使用itertools.product
  2. 逐一创建符号
  3. Add(*[...])格式比sum([...])更为有效,可以形成带有大量术语的符号和,请参见
  1. symarray depends on NumPy, but this does not seem to be an issue for you. If it was, I would create symbols one by one using itertools.product
  2. The format Add(*[...]) is more efficient than sum([...]) for forming symbolic sums with a large number of terms, see SymPy issue 13945.

这篇关于如何在SymPy中生成给定维的符号多元多项式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆