gmpy2.div给出TypeError:不支持div()参数类型

问题描述 投票:-1回答:1

我正在尝试使用sci-py中的盆地跳跃算法来最小化功能。这是我的代码:

from math import *
import time
import gmpy2
from gmpy2 import mpz
from gmpy2 import mpq,mpfr,mpc
import numpy as np
from scipy.optimize import basinhopping
minimizer_kwargs = {"method": "BFGS"}


s=mpz('2')
x0=[153000]
b = mpfr('6097781399')
estimator1=gmpy2.div(x0, s)-gmpy2.sqrt(((pow(x0,s)/4)-b))
estimator2=gmpy2.div(x0, s)+gmpy2.sqrt(((pow(x0,s)/4)-b))

c=mpfr(estimator1)
d=mpfr(estimator2)
e=mpz(b)

func = lambda x: abs((c*d)-e)

ret = basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs,
niter=400)
print("global minimum: x = %.4f, f(x0) = %.4f" % (ret.x, ret.fun))

读取完整错误

追踪(最近一次通话):文件“ anneal.py”,第14行,在estimator1 = gmpy2.div(x0,s)-gmpy2.sqrt(((pow(x0,s)/ 4)-b) )TypeError:不支持div()参数类型

我基本上想实现的目标是使abs((c*d)-e)最小化,但是我得到了一个错误:TypeError: div() argument types not supported。我已经用Google搜索这个错误了,也许这是因为变量和列表之间的类型不匹配。因此,我的问题是我应该如何重新制定estimator1estimator2的公式,以便能够将其传递到水池跳跃最小化器中。

编辑:

更正后的代码现在已读取(也删除了不必要的导入):

from math import *
from scipy.optimize import basinhopping
minimizer_kwargs = {"method": "BFGS"}
def f(x):

    b = 6097781399
    estimator1=(x/2)-sqrt(abs((pow(x,2)/4)-b))
    estimator2=(x/2)+sqrt(abs((pow(x,2)/4)-b))
    return abs((estimator1*estimator2)-b)

x = 110000
ret = basinhopping(f, x, minimizer_kwargs=minimizer_kwargs,
niter=2000)
print("global minimum: x = %.4f, f(x0) = %.4f" % (ret.x, ret.fun))
python optimization scipy minimization
1个回答
0
投票

我认为问题是您正在将python list传递到gmpy2.divC代码检查intrationalrealcomplex,如果都不适合,则会引发您提到的错误。尝试将x0作为整数传递。

[此外,我不认为scipy对您要传入的mpz(2)会感到高兴,scipy通常与python listsscipy.sparse矩阵或密集numpy.ndarray一起使用。] >

关于在python中处理大量数字,int是无界的(https://docs.python.org/3.6/library/stdtypes.html#typesnumeric)。当您需要数值稳定的运算时,NumPy也是一个不错的地方,numpy具有它自己的类型系统,具有64位floatint和128位复数。

https://docs.scipy.org/doc/numpy/user/basics.types.html

© www.soinside.com 2019 - 2024. All rights reserved.