【问题标题】:Why does np.linalg.solve give me an error when trying to solve a 16x16 system of equations?为什么在尝试求解 16x16 方程组时 np.linalg.solve 会给我一个错误?
【发布时间】:2022-01-23 02:35:02
【问题描述】:

我正在创建一个最大值为 n**n 的 nxn 矩阵。 np.linalg.solve 在 n = 16,它会给出错误:

numpy.core._exceptions.UFuncTypeError: Cannot cast ufunc 'solve1' input 0 from dtype('O') to dtype('float64') with casting rule 'same_kind'

这是我的代码:

import numpy as np

def fib_to(n):
    if n==0: return [0]
    fibs = [0, 1]
    for i in range(2, n+1):
        fibs.append(fibs[-1] + fibs[-2])
    return fibs

def get_nth_matrix(n):
    coeficients = [[i**j for j in range(n, -1, -1)] for i in range(n+1)]
    augment = fib_to(n)
    return coeficients, augment

print(np.linalg.solve(*get_nth_matrix(16)))

我还注意到在矩阵上执行np.linalg.cond 有同样的问题。它适用于高达 15 的值,但当 n 为 16 或更大时,除以 0 错误

【问题讨论】:

  • 对于 n>15,您的值太大而无法转换为 np.int32。如果您使用的是 Windows,则它是 np.array 的默认 dtype。我不知道np.linalg.solve 的实现。如果遇到OverflowError: Python int too large to convert to C long,可能会尝试默认为object

标签: python numpy matrix runtime-error linear-algebra


【解决方案1】:

get_nth_matrix(16) 返回的列表列表包含太大而无法放入 numpy 整数类型的整数。当您使用np.linalg.solve() 时,此列表列表将转换为 numpy 数组,但由于此大小问题,它会生成一个 python 对象数组。由于np.linalg.solve() 无法处理这种类型的数组,因此发生错误。您可以将get_nth_matrix()的最后一行替换为

return np.array(coeficients, dtype=float), augment

解决这个问题 - 至少对于不会溢出浮点类型的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 2013-11-14
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多