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

如何将整数数组及三维整数数组转换为SymPy有理矩阵?

Convert 3D Integer Array to SymPy Rational Matrix

I'll walk you through exactly how to turn your 3D integer array into a SymPy matrix of rational numbers using the Rational and Matrix classes you mentioned. Let's break this down with your example input.

Step 1: Understand the Input Structure

Your input array [[[2, 1], [1, 3], [3, 2]], [[4, 3], [5, 2], [0, 1]]] is structured as:

  • 2 outer sublists (each will become a row in the final matrix)
  • Each outer sublist contains 3 integer pairs, where each pair [a, b] translates to the rational number a/b

Step 2: Import Required SymPy Tools

First, make sure SymPy is installed, then import the classes we need:

from sympy import Rational, Matrix

Step 3: Convert Pairs to Rational Numbers

We'll iterate through the 3D array, convert each integer pair to a Rational object, and collect them into a flat list. A list comprehension makes this concise:

# Your input 3D array
input_array = [[[2, 1], [1, 3], [3, 2]], [[4, 3], [5, 2], [0, 1]]]

# Convert each [numerator, denominator] pair to a SymPy Rational
rational_elements = [Rational(num, den) for row in input_array for num, den in row]

Step 4: Build the SymPy Matrix

Pass the flat list of Rational elements to Matrix, specifying the shape (2 rows, 3 columns) to match your input's structure:

# Create a 2x3 matrix from the rational values
rational_matrix = Matrix(2, 3, rational_elements)

# Print the result
print(rational_matrix)

Step 5: Check the Output

When you run this code, you'll get exactly the matrix you're expecting:

Matrix([
[2, 1/3, 3/2],
[4/3, 5/2, 0]])

Key Notes

  • Using Rational guarantees exact fractional representation (no floating-point inaccuracies), which is critical for SymPy's symbolic math capabilities.
  • If your input size varies, you can calculate the matrix shape dynamically instead of hardcoding it (e.g., num_rows = len(input_array), num_cols = len(input_array[0])).
  • Double-check that all denominators are non-zero—SymPy will throw an error if you try to create a Rational with a denominator of 0.

内容的提问来源于stack exchange,提问作者LOL

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:28:02