You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SymPy中基于dim和terms变量创建指定维度的数组?

Solution for Creating Dynamic Multi-Dimensional Arrays in SymPy

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=3 and terms=4, this will create a MutableDenseNDimArray with shape (4,4,4)
  • When dim=3 and terms=3, you'll get a shape of (3,3,3)
  • This pattern works for any positive integer values of dim and terms

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:42:50