是否可以在 numpy.linalg 中强制执行整数运算?

Is it possible to enforce integer operations in numpy.linalg?

如果用np.linalg.solve求解一次方程组,结果有dtype=float

虽然这对 "small" 整数没问题,但较大的整数会导致错误的结果:

import numpy as np
A = np.array([[1000000000000,2000000],[3000000000000,4000000]])
x = np.array([1000000,2000000])
np.linalg.solve(A, A @ x)

结果

array([1000000.      , 1999999.999872])

我的问题不是,为什么会出现错误,我知道这一点。我也知道 numpy 整数的限制是由 C 整数决定的。

但是,有没有办法 using/enforcing 在 np.linalg 中使用大 (r) 整数?

我发现了这个:,但这在 np.linalg.solve:

中不起作用
/usr/lib/python3/dist-packages/numpy/linalg/linalg.py in solve(a, b)
    401     signature = 'DD->D' if isComplexType(t) else 'dd->d'
    402     extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
--> 403     r = gufunc(a, b, signature=signature, extobj=extobj)
    404 
    405     return wrap(r.astype(result_t, copy=False))

TypeError: No loop matching the specified signature and casting
was found for ufunc solve1

在这种情况下,您可能想使用 mpmath instead of numpy. It has linear algebra routines

np.linalg.solve is a wrapper around LAPACK:

The solutions are computed using LAPACK routine _gesv.

BLAS/LAPACK 都是关于浮点计算的!商业实现(例如英特尔 MKL)可能支持一些基于整数的功能,并且在 OpenBLAS 上存在非常有限的experimental branch

但是 numpy 支持多个 BLAS/LAPACK-backends,因此只支持所有地方都支持的。这些是基于浮点数的操作。

出于好奇,您可以阅读 umath_linalg.c.src 中的一些内容,其中所有这些类型都很容易识别。有了这些 类型的源代码 就很容易看出,为什么某些基于 np.object 的数组不起作用。