I'm trying to minimize a function with basin-hopping algorithm in sci-py. Here is my code:
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))
the full error reads
Traceback (most recent call last): File "anneal.py", line 14, in estimator1=gmpy2.div(x0, s)-gmpy2.sqrt(((pow(x0,s)/4)-b)) TypeError: div() argument types not supported
What I'm basically trying to achieve is minimizing abs((c*d)-e)
, however I get an error as: TypeError: div() argument types not supported
. I have Googled about this error and perhaps the cause of this is a type mismatch between a variable and a list. So my question is how should I re-formulate estimator1
and estimator2
to be able to pass it into basin-hopping minimizer.
Edit:
Corrected code now reads (also removed unnecessary imports):
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))