如何在SymPy中基于dim和terms变量创建指定维度的数组?
Got it, let's figure out how to replicate that NumPy-style dynamic array creation in SymPy for your use case. The core issue is that SymPy's zeros function works differently than NumPy's—instead of accepting a single shape tuple, it expects individual dimension sizes as arguments. But we can work around this easily to get exactly the MutableDenseNDimArray you want.
Step-by-Step Implementation
First, import the necessary SymPy components:
from sympy import zeros, MutableDenseNDimArray
Then, define your dim and terms variables (these can be any positive integers you need):
dim = 2 terms = 4
Now, we'll dynamically generate the shape tuple and create your array:
# Create the shape tuple (e.g., (4,4) when dim=2, (4,4,4) when dim=3) shape = (terms,) * dim # First make a flat array of zeros with total elements = terms^dim flat_zeros = zeros(terms ** dim) # Convert the flat array into the multi-dimensional array you need m = MutableDenseNDimArray(flat_zeros, shape)
Shorter Alternative
If you prefer a more concise approach, you can directly unpack the shape tuple into SymPy's zeros function, then wrap it in MutableDenseNDimArray:
shape = (terms,) * dim m = MutableDenseNDimArray(zeros(*shape))
Testing Different Cases
- When
dim=3andterms=4, this will create aMutableDenseNDimArraywith shape(4,4,4) - When
dim=3andterms=3, you'll get a shape of(3,3,3) - This pattern works for any positive integer values of
dimandterms
The key here is using Python's tuple multiplication (terms,) * dim to generate the dynamic shape, then adapting it to SymPy's API either by creating a flat array first or unpacking the shape into zeros.
内容的提问来源于stack exchange,提问作者Ryan O'Connor

