python - 精度损失 numpy - mpmath

标签 python arrays numpy mpmath

我在我的 Python 程序中使用 numpy 和 mpmath。我使用 numpy,因为它允许轻松访问许多线性代数运算。但是因为 numpy 的线性方程求解器不是那么精确,所以我使用 mpmath 进行更精确的运算。在我计算出系统的解决方案之后:

solution = mpmath.lu_solve(A,b)

我想要一个数组形式的解决方案。所以我用

array = np.zeros(m)

然后循环设置值:

for i in range(m):
    array[i] = solution[i]

for i in range(m):
    array.put([i],solution[i])

但是通过这两种方式我都会再次遇到数值不稳定性,例如:

solution[0] = 12.375
array[0] = 12.37500000000000177636

有没有办法避免这些错误?

最佳答案

numpy ndarrays 具有同类类型。当你创建 array 时,默认的 dtype 将是某种类型的 float ,它没有你想要的精度:

>>> array = np.zeros(3)
>>> array
array([ 0.,  0.,  0.])
>>> array.dtype
dtype('float64')

您可以使用 dtype=object 来解决这个问题:

>>> mp.mp.prec = 65
>>> mp.mpf("12.37500000000000177636")
mpf('12.37500000000000177636')
>>> array = np.zeros(3, dtype=object)
>>> array[0] = 12.375
>>> array[1] = mp.mpf("12.37500000000000177636")
>>> array
array([12.375, mpf('12.37500000000000177636'), 0], dtype=object)

但请注意,执行此操作会严重影响性能。

关于python - 精度损失 numpy - mpmath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21165745/

相关文章:

c++ - 如果另一个相同值的数组元素已经在 C++ 中回显,则防止循环回显

Python:如何使用 1 个 lambda 函数进行多种浮点格式设置

python - 如何保存请求参数以及Flask异常?

Python——从文件中读取行并拆分它

javascript - Python 与 JavaScript 交互?

python - 如何检查 JSON 数组中是否存在值并继续循环

python - 考虑 NaN 的 Numpy cumsum

python - 如何从 pandas.DatetimeIndex 转换为 numpy.datetime64?

python array.tostring() 中有 NUL 字节

python : Behaviour of send() in generators