Skip to content Skip to sidebar Skip to footer

How To Generate A Symbolic Multivariate Polynomial Of A Given Dimension In Sympy?

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

Solution 1:

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 inzip(x, p)]) for p in prod_iterator])

The result being

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**2*x_3 + a_0_2_0_2*x_1**2*x_3**2 + a_0_2_1_0*x_1**2*x_2 + a_0_2_1_1*x_1**2*x_2*x_3 + a_0_2_1_2*x_1**2*x_2*x_3**2 + a_0_3_0_0*x_1**3 + a_0_3_0_1*x_1**3*x_3 + a_0_3_0_2*x_1**3*x_3**2 + a_0_3_1_0*x_1**3*x_2 + a_0_3_1_1*x_1**3*x_2*x_3 + a_0_3_1_2*x_1**3*x_2*x_3**2 + a_1_0_0_0*x_0 + a_1_0_0_1*x_0*x_3 + a_1_0_0_2*x_0*x_3**2 + a_1_0_1_0*x_0*x_2 + a_1_0_1_1*x_0*x_2*x_3 + a_1_0_1_2*x_0*x_2*x_3**2 + a_1_1_0_0*x_0*x_1 + a_1_1_0_1*x_0*x_1*x_3 + a_1_1_0_2*x_0*x_1*x_3**2 + a_1_1_1_0*x_0*x_1*x_2 + a_1_1_1_1*x_0*x_1*x_2*x_3 + a_1_1_1_2*x_0*x_1*x_2*x_3**2 + a_1_2_0_0*x_0*x_1**2 + a_1_2_0_1*x_0*x_1**2*x_3 + a_1_2_0_2*x_0*x_1**2*x_3**2 + a_1_2_1_0*x_0*x_1**2*x_2 + a_1_2_1_1*x_0*x_1**2*x_2*x_3 + a_1_2_1_2*x_0*x_1**2*x_2*x_3**2 + a_1_3_0_0*x_0*x_1**3 + a_1_3_0_1*x_0*x_1**3*x_3 + a_1_3_0_2*x_0*x_1**3*x_3**2 + a_1_3_1_0*x_0*x_1**3*x_2 + a_1_3_1_1*x_0*x_1**3*x_2*x_3 + a_1_3_1_2*x_0*x_1**3*x_2*x_3**2 + a_2_0_0_0*x_0**2 + a_2_0_0_1*x_0**2*x_3 + a_2_0_0_2*x_0**2*x_3**2 + a_2_0_1_0*x_0**2*x_2 + a_2_0_1_1*x_0**2*x_2*x_3 + a_2_0_1_2*x_0**2*x_2*x_3**2 + a_2_1_0_0*x_0**2*x_1 + a_2_1_0_1*x_0**2*x_1*x_3 + a_2_1_0_2*x_0**2*x_1*x_3**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

Remarks:

  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.

Post a Comment for "How To Generate A Symbolic Multivariate Polynomial Of A Given Dimension In Sympy?"