
本文探讨了如何将一维 NumPy 数组重塑为尽可能接近正方形的二维矩阵,即找到两个因子 p 和 q,使得 p * q 等于数组长度 n,且 p 尽可能接近 sqrt(n)。文章提供了两种实现方法:一种是速度更快的简单方法,适用于较小的 n;另一种是更通用的方法,基于质因数分解和幂集搜索,适用于更复杂的情况。同时,文章也给出了示例代码,展示了如何使用这些方法进行数组重塑。
在数据处理和分析中,经常需要将一维数组转换为二维矩阵。当需要将数据可视化或进行矩阵运算时,这种转换尤为重要。如果希望得到的矩阵尽可能接近正方形,就需要找到合适的行数和列数。 本文将介绍如何使用 NumPy 实现这一目标。
核心问题在于找到两个整数 p 和 q,使得它们的乘积等于给定数 n,并且 p 和 q 的差值尽可能小。换句话说,我们需要找到最接近 sqrt(n) 的 n 的因子。
以下代码提供了一种简单且快速的方法来找到最接近正方形的因子。该方法通过遍历小于 sqrt(n) 的所有整数,找到能够整除 n 的最大整数。
import numpy as np
from math import isqrt
def np_squarishrt(n):
a = np.arange(1, isqrt(n) + 1, dtype=int)
b = n // a
i = np.where(a * b == n)[0][-1]
return a[i], b[i]代码解释:
使用示例:
n = 500
p, q = np_squarishrt(n)
print(f"Factors of {n}: {p}, {q}") # Output: Factors of 500: 20, 25
a = np.arange(500)
b = a.reshape(np_squarishrt(len(a)))
print(b.shape) # Output: (20, 25)如果 n 的因子比较复杂,或者需要更精确的控制,可以使用基于质因数分解和幂集搜索的方法。
from itertools import chain, combinations
from math import isqrt
def factors(n):
i = 2
while i * i <= n:
if n % i:
i += 1
else:
n //= i
yield i
if n > 1:
yield n
def uniq_powerset(iterable):
"""
Similar to powerset(it) but without repeats.
uniq_powerset([1,1,2]) --> (), (1,), (2,), (1, 1), (1, 2), (1, 1, 2)
"""
s = list(iterable)
return chain.from_iterable(set(combinations(s, r)) for r in range(len(s)+1))
def squarishrt(n):
p = isqrt(n)
if p**2 == n:
return p, p
bestp = 1
f = list(factors(n))
for t in uniq_powerset(f):
if 2 * len(t) > len(f):
break
p = np.prod(t) if t else 1
q = n // p
if p > q:
p, q = q, p
if p > bestp:
bestp = p
return bestp, n // bestp代码解释:
使用示例:
n = 500
p, q = squarishrt(n)
print(f"Factors of {n}: {p}, {q}") # Output: Factors of 500: 20, 25
a = np.arange(500)
b = a.reshape(squarishrt(len(a)))
print(b.shape) # Output: (20, 25)本文介绍了两种将一维 NumPy 数组重塑为接近正方形的二维矩阵的方法。第一种方法适用于较小的数字,速度更快。第二种方法适用于更复杂的情况,但计算量更大。 通过这些方法,可以灵活地将一维数组转换为二维矩阵,以便进行后续的数据处理和分析。在实际应用中,可以根据数据规模和性能要求选择合适的方法。
以上就是将一维数组重塑为接近正方形的矩阵的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号