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

如何使用Sympy对矩阵元素逐元素取模n?

How to Compute a Matrix with Elements Modulo n Using SymPy

Absolutely, SymPy has straightforward ways to create a new matrix where every element is taken modulo n—you don’t need NumPy for this task! Here are two reliable methods:

Method 1: Use the % Operator (Simplest Approach)

SymPy’s Matrix class overloads the modulo operator (%), so you can directly apply it to the entire matrix and your modulus n. This works exactly like NumPy’s element-wise modulo operation.

Example Code:

from sympy import Matrix

# Define your original matrix and modulus
original_mat = Matrix([[7, 12], [15, 20]])
n = 5

# Compute element-wise modulo
mod_mat = original_mat % n

print(mod_mat)
# Output:
# Matrix([[2, 2], [0, 0]])

Method 2: Use applyfunc() for Custom Logic

If you need more control over the modulo operation (e.g., handling negative numbers in a specific way), you can use Matrix.applyfunc() to pass a custom function that processes each element.

Example Code:

from sympy import Matrix

original_mat = Matrix([[-3, 12], [15, -7]])
n = 5

# Custom modulo function (ensures non-negative results)
def custom_mod(x):
    return x % n

mod_mat = original_mat.applyfunc(custom_mod)

print(mod_mat)
# Output:
# Matrix([[2, 2], [0, 3]])

Bonus: Works with Symbolic Elements Too

SymPy’s strength is symbolic computation, and both methods work seamlessly with symbolic variables:

from sympy import Symbol, Matrix

x = Symbol('x')
symbolic_mat = Matrix([[x, x+3], [2*x, x-1]])
n = 4

mod_symbolic_mat = symbolic_mat % n

print(mod_symbolic_mat)
# Output:
# Matrix([[x mod 4, (x + 3) mod 4], [2*x mod 4, (x - 1) mod 4]])

Either method will give you the element-wise modulo matrix you need—pick the one that fits your use case best!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:04:31