http://www.cs.bham.ac.uk/~jer/papers/ctsgray.pdf
Code: Select all
function continuousGray(x as double,precision as double=20) as double
dim as double y
if rnd>.5 then
y=x+exp(-precision*rnd)
if y>1.0 then y-=2.0
else
y=x-exp(-precision*rnd)
if y<-1.0 then y+=2.0
end if
return y
end function
sub translate(result() as double,vec() as double,minX() as double,maxX() as double)
dim as integer i
for i=0 to ubound(result)
result(i)=minX(i)+.5*(vec(i)+1.0)*(maxX(i)-minX(i))
next
end sub
sub optimize(fn as function(X() AS DOUBLE) AS DOUBLE, minX() as double,maxX() as double,res() as double,iterations as uinteger,p as double=20)
dim as double vecA(ubound(res)),vecB(ubound(res)),cost,tc
dim as uinteger i,iter
randomize timer,3
for i=0 to ubound(res)
res(i)=1-2.0*rnd
next
translate(vecB(),res(),minX(),maxX())
cost=fn(vecB())
for iter=0 to iterations
for i=0 to ubound(res)
vecA(i)=continuousGray(res(i),p)
next
translate(vecB(),vecA(),minX(),maxX())
tc=fn(vecB())
if tc<cost then
cost=tc
for i=0 to ubound(res)
res(i)=vecA(i)
next
end if
next
translate(res(),res(),minX(),maxX())
end sub
'Demo
' minimum -18.5547... at (9.039, 8.668)
function test(v() as double) as double
return v(0)*sin(4*v(0))+1.1*v(1)*sin(2*v(1))
end function
dim x(1) as double=>{0,0}
dim min(1) as double=>{0,0}
dim max(1) as double=>{10,10}
optimize(@test,min(),max(),x(),1000,20)
print test(x())
getkey