如何将整数数组及三维整数数组转换为SymPy有理矩阵?
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 numbera/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
Rationalguarantees 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
Rationalwith a denominator of 0.
内容的提问来源于stack exchange,提问作者LOL

