我不是新编程,但我是Python和数值计算的新手,所以这可能是一个新手问题。
我使用GMPY2来处理极大数字的计算,但我想使用MatPlotLib来绘制结果图。我目前有
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))
我认为没有从mpfr到numpy的本机类型的隐式转换。在np.arange
中,我尝试设置dtype=mpfr
,并在plot
方法中尝试编写hop(mpfr(t), mpfr(t), 0)
,但当然没有运气。
答案 0 :(得分:0)
免责声明:我保留gmpy2
。
由于您没有说明错误消息,我尝试了您的代码并遇到以下错误消息:
TypeError: add() argument types not supported
gmpy2
函数只接受标量参数。它们不会遍历列表。您需要手动执行此操作。
t = np.arange(-5.0, 5.0, 0.01)
hopt = [hop(x, x, 0) for x in t]
plt.plot(t, hopt)
更新
以下是显示mpfr_range()
功能的示例。
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()