Reputation: 21
I have a problem with numpy,I use the numpy.min() to get expression's minimum value,but when I get the minimum value,how can i get the x and y value on the contrary.The x,y was in the expression.,
x=np.linspace(-300,300,10000)
y=np.linspace(-300,300,10000)
D=np.min((np.sqrt((x)**2+(y)**2)-2))**2+(np.sqrt((x-3)**2+(y-2)**2)-2)**2)
I write the f() as u teach me like this:
def f(self,xy,k):
expression=0
x, y= xy
cols=self.maintablewidget.columnCount()-1
#for k in range(3,cols):
for i in range(1,k):
d=string.atof(self.maintablewidget.item(i-1,k-1).text())
xi=string.atof(self.xytablewidget.item(i-1,0).text())
yi=string.atof(self.xytablewidget.item(i-1,1).text())
expression=np.sum((np.sqrt((x-xi)**2+(y-yi)**2)-d)**2)
return expression
#I do not know how to call the f() here, because the parameter k I do not know pass it
for k in range(3,12):
res=optimize.minimize(self.f,(0,0),k)#here is an error
print(res['x'][0])
print(res['x'],res['fun'])
I do not know how to pass the K to f(self,xy,k),when i call it !
Upvotes: 0
Views: 384
Reputation: 879103
Using scipy, you could try to find the minimum of the function using optimize.minimize
:
import numpy as np
from scipy import optimize
def f(xy):
x, y = xy
return (np.sqrt((x)**2+(y)**2)-2)**2+(np.sqrt((x-3)**2+(y-2)**2)-2)**2
res = optimize.minimize(f, (0,0))
This shows x
and y
value coorsponding to the minimum of f
:
print(res['x'])
# [ 1.01961249 1.72058165]
This is the minimum value of f
found:
print(res['fun'])
# 1.27566100252e-11
optimize.minimize
uses the BFGS
algorithm
by default when there are no bounds or constraints.
As cel points out, you could also use optimize.brute
to do a brute force
search for the minimum:
In [68]: optimize.brute(f, (slice(-300, 300, 10000), slice(-300, 300, 10000)))
Out[68]: array([ 1.98035504, 0.27946845])
Brute can be use to find interesting starting points which can then by
"polished" by other algorithms. For example, you can use optimize.minimize
to
polish the point found by brute:
def minimize_wrapper(func, xmin, args, full_output, disp):
res = optimize.minimize(func, xmin, args)
return res['x'], res['fun']
z, fval, grid, Jout = optimize.brute(
f, (slice(-300, 300, 1000), slice(-300, 300, 1000)),
finish=minimize_wrapper, full_output=True)
This is the (x,y) location found:
print(z)
# array([ 1.98038404, 0.27942339])
and this is the corresponding value of f
:
print(fval)
# 1.8566073609451249e-13
Upvotes: 1