I want to have a numpy array with mpz/mpfr values. Because my code:
import numpy as np
import gmpy2
A=np.ones((5,5));
print A/gmpy2.mpfr(1);
generates:
RuntimeWarning: invalid value encountered in divide
print A/gmpy2.mpfr(1);
[[1.0 1.0 1.0 1.0 1.0]
[1.0 1.0 1.0 1.0 1.0]
[1.0 1.0 1.0 1.0 1.0]
[1.0 1.0 1.0 1.0 1.0]
[1.0 1.0 1.0 1.0 1.0]]
Which as I can understand is the impossibility to convert gmpy mpfr to numpy float64. So how can I get a numpy array with mpfr values in the first place?
Thanks.
You will need to create your array with dtype=object
, and then you can use any python type inside your array. I don't have gmpy2 installed, but the following example should show how it works:
In [3]: a = np.ones((5, 5), dtype=object)
In [5]: import fractions
In [6]: a *= fractions.Fraction(3, 4)
In [7]: a
Out[7]:
array([[3/4, 3/4, 3/4, 3/4, 3/4],
[3/4, 3/4, 3/4, 3/4, 3/4],
[3/4, 3/4, 3/4, 3/4, 3/4],
[3/4, 3/4, 3/4, 3/4, 3/4],
[3/4, 3/4, 3/4, 3/4, 3/4]], dtype=object)
Having a numpy array of dtype=object
can be a liitle misleading, because the powerful numpy machinery that makes operations with the standard dtypes super fast, is now taken care of by the default object's python operators, which means that the speed will not be there anymore:
In [12]: b = np.ones((5, 5)) * 0.75
In [13]: %timeit np.sum(a)
1000 loops, best of 3: 1.25 ms per loop
In [14]: %timeit np.sum(b)
10000 loops, best of 3: 23.9 us per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With