Search code examples
pythonarraysnumpympmath

Precision loss numpy - mpmath


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?


Solution

  • 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.