Twiffy - 11 months ago 73

Python Question

I'm not new to programming, but I am new to Python and numerical computing, so this may be a newbie question.

I'm using GMPY2 to handle computation of extremely large numbers, but I want to use MatPlotLib to graph the results. I currently have

`import gmpy2`

from gmpy2 import mpz, mpq, mpfr, mpc

import numpy as np

import matplotlib.pyplot as plt

gmpy2.get_context().precision = 100

def hop(x, y, n):

if n > 0:

return gmpy2.exp(hop(gmpy2.log(x), gmpy2.log(y), n-1))

elif n == 0:

return gmpy2.add(x, y)

else:

raise ValueError('Negative value of n in hop method.')

t = np.arange(-5.0, 5.0, 0.01)

plt.plot(t, hop(t, t, 0))

I assume there's no implicit conversion from mpfr to numpy's native type. In

`np.arange`

`dtype=mpfr`

`plot`

`hop(mpfr(t), mpfr(t), 0)`

Answer

Disclaimer: I maintain `gmpy2`

.

Since you didn't state your error message, I tried your code and encountered the following error message:

```
TypeError: add() argument types not supported
```

The `gmpy2`

functions only accept scalar arguments. They do not iterate over a list. You will need to do that manually.

```
t = np.arange(-5.0, 5.0, 0.01)
hopt = [hop(x, x, 0) for x in t]
plt.plot(t, hopt)
```

Update

Here is an example showing an `mpfr_range()`

function.

```
import gmpy2
from gmpy2 import mpfr, exp, log
import matplotlib.pyplot as plt
gmpy2.get_context().precision = 100
def mpfr_range(first, last, n):
'''Yield a sequence of n mpfr values that range from first
to last. Both first and last are included. n must be greater
than or equal to 2.'''
n = int(n)
first = mpfr(first)
last = mpfr(last)
if n < 2:
raise ValueError('n must be >= 2')
if last <= first:
raise ValueError('last must be > first')
delta = (last - first) / (n - 1)
for i in range(n - 1):
yield first + i * delta
yield last
def hop(x, y, n):
if n > 0:
return exp(hop(log(x), log(y), n-1))
elif n == 0:
return x + y
else:
raise ValueError('Negative value of n in hop method.')
# It is recommended to initialize mpfr instances from exact values -
# either a string or an integer for this use.
t = list(mpfr_range('10', '20', 20))
hopt = [hop(x, x, 0) for x in t]
plt.plot(t, hopt)
plt.show()
```