precision损失numpy的 - mpmath [英] Precision loss numpy - mpmath
问题描述
我使用numpy的和mpmath在我的Python PROGRAMM。我使用numpy的,因为它允许一个容易获得许多线性代数运算。但由于numpy的对线性方程组的求解是不是准确,我用mpmath更多precision操作。之后,我计算系统的解决方案:
解决方案= mpmath.lu_solve(A,B)
我想该解决方案作为一个数组。所以我用
=阵列np.zeros(M)
,然后做一个循环设置值:
为我在范围内(米):
数组[我] =解决方案[I]
或
为我在范围内(米):
array.put([Ⅰ],溶液[I])
但有两种方式,我得到再次数值不稳定性,如:
解决方案[0] = 12.375
数组[0] = 12.37500000000000177636
有没有办法来避免这些错误?
numpy的
ndarrays有均匀型。当您阵列
,默认 DTYPE
会有一些float类型,它不拥有尽可能多的precision你想要的:
>>>阵= np.zeros(3)
>>>排列
阵列([0,0,0])
>>> array.dtype
DTYPE('float64')
您可以使用 DTYPE =对象
解决这个问题
>>> mp.mp. preC = 65
>>> mp.mpf(12.37500000000000177636)
强积金('12 0.37500000000000177636')
>>>阵列= np.zeros(3 DTYPE =对象)
>>>数组[0] = 12.375
>>>阵列[1] = mp.mpf(12.37500000000000177636)
>>>排列
阵列([12.375,MPF('12 0.37500000000000177636'),0],DTYPE =对象)
但请注意,有一个显著的性能损失,当你做到这一点。
I use numpy and mpmath in my Python programm. I use numpy, because it allows an easy access to many linear algebra operations. But because numpy's solver for linear equations is not that exact, i use mpmath for more precision operations. After i compute the solution of a System:
solution = mpmath.lu_solve(A,b)
i want the solution as an array. So i use
array = np.zeros(m)
and then do a loop for setting the values:
for i in range(m):
array[i] = solution[i]
or
for i in range(m):
array.put([i],solution[i])
but with both ways i get again numerical instabilities like:
solution[0] = 12.375
array[0] = 12.37500000000000177636
Is there a way to avoid these errors?
numpy
ndarrays have homogeneous type. When you make array
, the default dtype
will be some type of float, which doesn't have as much precision as you want:
>>> array = np.zeros(3)
>>> array
array([ 0., 0., 0.])
>>> array.dtype
dtype('float64')
You can get around this by using 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)
but note that there's a significant performance hit when you do this.
这篇关于precision损失numpy的 - mpmath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!