I have a function which is multivariate (code below), depending on x1
and x2
and I have a target output value in mind for this function, named target
. I fix x1
and provide my target
in the outer function: find_x2
. The objective is to minimize the inner function error
, which is just the squared distance between my output target and the resulting value est
, with respect to x2
.
But having run it:
find_x2(target = .12, x1 = 100)
yields x2 = 0.99899
, but it should be roughly .80
.
It appears the function is minimizing with respect to est
instead of x2
, but I can't see why. Any help would be appreciated.
Code:
import numpy as np
from scipy.optimize import minimize_scalar, minimize
def find_x2(x1, target):
def error(x2, x1 = x1, target = target):
k = np.zeros(x1)
V = np.zeros(x1)
for i in range(x1):
try:
k[i-1] = (i/x1)**(-1/x2)
except:
k[x1-1]=1
for i in range(x1):
V[i] = k[i]/sum(k)
est = sum(V**2)
return (target - est)**2
return minimize_scalar(error, bounds = (.001,.999), method = 'bounded')
CodePudding user response:
Try this version:
def find_x2(x1, target):
def error(x2, x1 = x1, target = target):
k = np.zeros(x1)
V = np.zeros(x1)
for i in range(x1):
try:
k[i-1] = (x1/i)**(1/x2)
except:
k[x1-1]=1
for i in range(x1):
V[i] = k[i]/sum(k)
est = sum(V**2)
return (target - est)**2
return minimize_scalar(error, bounds = (.001,.999), method = 'bounded')
find_x2(100, 0.12)
prints
fun: 9.668753433849857e-14
message: 'Solution found.'
nfev: 14
status: 0
success: True
x: 0.801701074855243