10

I have a numpy array A with mpf elements that have decimal precision 100. Is this precision cast away if I decide to take the numpy dot product of A with itself?

If this is the case, is there any way to convert a numpy array to an mpmath matrix, so I can keep the precision?

Jing
  • 313
  • 1
  • 3
  • 7
  • 2
    I doubt it'll cause problems. `dot` works fine when I test it with arrays full of `fractions.Fraction` instances, so it'll probably call the appropriate `mpmath` methods without trying to cast to numpy floats. I recommend trying it. – user2357112 Mar 01 '14 at 11:53
  • Thanks :) I have been trying to look for documentation on which numpy operations work well with mpmath, but unfortunately no luck so far :( – Jing Mar 01 '14 at 12:02

2 Answers2

15

Numpy arrays can hold objects, in particular mpf objects, and their methods such as dot can use the addition/multiplication methods of these objects. Example:

import mpmath
import numpy
mpmath.mp.dps = 25     # higher precision for demonstration
a = [mpmath.sin(mpmath.pi*n/3) for n in range(99)]
b = numpy.array(a)
b.dot(b)

outputs mpf('49.50000000000000000000000165')

For comparison, this is what happens if the array elements are cast to double-precision floats when converting to numpy:

c = numpy.array(a, dtype=float)
c.dot(c)

outputs 49.499999999999993. So, the higher precision provided by mpmath is preserved when the dot method is invoked in the first version.

1

The previous answer is correct. However, sometimes there are things that are working in numpy and it is not working in mpmath (at least it is done in a different way). Hence, the original (general) question of

"...is there any way to convert a numpy array to an mpmath matrix, so I can keep the precision?.."

In my experience, this (more general) question still needs to have a general answer. One of the answers to this problem is to convert the numpy array first to list then List to mpmath matrix.

Here is a simple example that works for me (warning, may not be efficient):

import mpmath as mp, numpy as np
N = 5
L = np.ones(N)
M = np.diag(L, 2) # A numpy matrix 7x7
# Notes that MPMath "diag" function is limited to one parameter only
M = mp.matrix(M.tolist())
print(type(M),'\n', M)
taufikedys
  • 319
  • 2
  • 10