using Statistics
R = [-2pi pi; 0 pi]
x = collect(range(-2pi,stop=pi/2,length=100))
y = collect(range(0,stop=pi,length=100))
f = contour(x,y,Fun,fill=true, levels=-20:2:20)
function validrect(f,xind,yind)
fsub = f[xind,yind]
npos = sum(fsub.>0)
nneg = sum(fsub.<0)
if npos == 4 || nneg == 4
return false
end
return true
end
function bisect2d(Fun,R,nsteps)
@show R
plot!([R[1,1] R[1,2] R[1,2] R[1,1] R[1,1]]',
[R[2,1] R[2,1] R[2,2] R[2,2] R[2,1]]')
Rinit = R
Rmid = [R[1,1] mean(R[1,:]) R[1,2]; R[2,1] mean(R[2,:]) R[2,2]]
R = Rmid
f = zeros(3,3)
for xi=1:3
for yi=1:3
f[xi,yi] = Fun(R[1,xi], R[2,yi])
end
end
if nsteps==0
return Rinit
end
@assert(validrect(f,[1,3],[1,3]))
if validrect(f,[1,2],[1,2])
return bisect2d(Fun,[R[1,1] R[1,2];R[2,1] R[2,2]],nsteps-1)
elseif validrect(f,[2,3],[1,2])
return bisect2d(Fun,[R[1,2] R[1,3];R[2,1] R[2,2]],nsteps-1)
elseif validrect(f,[1,2],[2,3])
return bisect2d(Fun,[R[1,1] R[1,2];R[2,2] R[2,3]],nsteps-1)
elseif validrect(f,[2,3],[2,3])
return bisect2d(Fun,[R[1,2] R[1,3];R[2,2] R[2,3]],nsteps-1)
else
@assert(false)
end
end
bisect2d(Fun,R,8)
f