Skip to content

Instantly share code, notes, and snippets.

@pkofod
Created July 22, 2019 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pkofod/69bb5fee1bbad09cb93c3799a69c3863 to your computer and use it in GitHub Desktop.
Save pkofod/69bb5fee1bbad09cb93c3799a69c3863 to your computer and use it in GitHub Desktop.
using StaticArrays
using NLSolvers
using LinearAlgebra
function himmelblau(∇²f, ∇f, x)
if !(∇²f == nothing)
∇²f11 = 12.0 * x[1]^2 + 4.0 * x[2] - 42.0
∇²f12 = 4.0 * x[1] + 4.0 * x[2]
∇²f21 = 4.0 * x[1] + 4.0 * x[2]
∇²f22 = 12.0 * x[2]^2 + 4.0 * x[1] - 26.0
∇²f = @SMatrix([∇²f11 ∇²f12; ∇²f21 ∇²f22])
end
if !(∇f == nothing)
∇f1 = 4.0 * x[1]^3 + 4.0 * x[1] * x[2] -
44.0 * x[1] + 2.0 * x[1] + 2.0 * x[2]^2 - 14.0
∇f2 = 2.0 * x[1]^2 + 2.0 * x[2] - 22.0 +
4.0 * x[1] * x[2] + 4.0 * x[2]^3 - 28.0 * x[2]
∇f = @SVector([∇f1, ∇f2])
end
fx = (x[1]^2 + x[2] - 11)^2 + (x[1] + x[2]^2 - 7)^2
if ∇f == nothing && ∇²f == nothing
return fx
elseif ∇²f == nothing
return fx, ∇f
else
return fx, ∇f, ∇²f
end
end
function himmelblau(∇f, x)
if !(∇f == nothing)
∇f1 = 4.0 * x[1]^3 + 4.0 * x[1] * x[2] -
44.0 * x[1] + 2.0 * x[1] + 2.0 * x[2]^2 - 14.0
∇f2 = 2.0 * x[1]^2 + 2.0 * x[2] - 22.0 +
4.0 * x[1] * x[2] + 4.0 * x[2]^3 - 28.0 * x[2]
∇f = @SVector([∇f1, ∇f2])
end
fx = (x[1]^2 + x[2] - 11)^2 + (x[1] + x[2]^2 - 7)^2
if ∇f == nothing
return fx
else
return fx, ∇f
end
end
res = minimize(himmelblau, @SVector([2.0,2.0]), Newton(Direct()))
@test norm(res[3], Inf) < 1e-8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment