Skip to content

Commit 41f6aaa

Browse files
committed
variational Problem - reviewed changes
1 parent a896e54 commit 41f6aaa

2 files changed

Lines changed: 32 additions & 33 deletions

File tree

src/ADNLPProblems/variational.jl

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,30 @@ export variational
22

33
function variational(; n::Int = default_nvar, type::Type{T} = Float64, kwargs...) where {T}
44
h = 1 // (n + 1)
5-
x0 = Vector{T}(undef, n)
6-
for i = 1:n
7-
x0[i] = i * h * (1 - i * h)
8-
end
9-
f =
10-
x -> begin
11-
xext = vcat(zero(eltype(x)), x, zero(eltype(x)))
12-
term1 = sum(x[i] * (x[i] - xext[i + 2]) / convert(eltype(x), h) for i = 1:n)
13-
term2 = sum(
14-
if eltype(x) <: AbstractFloat
15-
d = xext[j + 2] - xext[j + 1]
16-
abs(d) <= eps(eltype(x)) ? exp(xext[j + 1]) : (exp(xext[j + 2]) - exp(xext[j + 1])) / d
17-
else
18-
d = xext[j + 2] - xext[j + 1]
19-
exp(xext[j + 1]) * expm1(d) / d
20-
end for j = 0:n
21-
)
22-
return 2 * (term1 + n * (convert(eltype(x), h) / 2) * term2)
5+
x0 = [
6+
begin
7+
ih = i * h
8+
convert(T, ih * (1 - ih))
9+
end for i = 1:n
10+
]
11+
12+
function f(x)
13+
term1 = zero(T)
14+
for i = 1:n
15+
xi = x[i]
16+
xip = (i < n) ? x[i + 1] : zero(T)
17+
term1 += xi * (xi - xip) / h
18+
end
19+
20+
term2 = zero(T)
21+
for j = 0:n
22+
a = (j == 0) ? zero(T) : x[j]
23+
b = (j == n) ? zero(T) : x[j + 1]
24+
term2 += (exp(b) - exp(a)) / (b - a)
2325
end
2426

27+
return 2 * (term1 + n * (h / 2) * term2)
28+
end
29+
2530
return ADNLPModels.ADNLPModel(f, x0, name = "variational"; kwargs...)
2631
end

src/PureJuMP/variational.jl

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,12 @@ export variational
1212

1313
function variational(; n::Int = default_nvar, kwargs...)
1414
h = 1 // (n + 1)
15-
x0 = [begin
16-
ih = i * h
17-
convert(Float64, ih * (1 - ih))
18-
end for i = 1:n]
15+
x0 = [
16+
begin
17+
ih = i * h
18+
convert(T, ih * (1 - ih))
19+
end for i = 1:n
20+
]
1921
model = Model()
2022
@variable(model, x[i = 1:n], start = x0[i])
2123

@@ -27,17 +29,9 @@ function variational(; n::Int = default_nvar, kwargs...)
2729
n *
2830
(h / 2) *
2931
(
30-
(1 + x[1]/2 + x[1]^2/6 + x[1]^3/24 + x[1]^4/120) +
31-
sum(
32-
exp(x[j]) * (
33-
1 +
34-
(x[j + 1] - x[j]) / 2 +
35-
(x[j + 1] - x[j])^2 / 6 +
36-
(x[j + 1] - x[j])^3 / 24 +
37-
(x[j + 1] - x[j])^4 / 120
38-
) for j = 1:(n - 1)
39-
) +
40-
exp(x[n]) * (1 + (0 - x[n]) / 2 + (0 - x[n])^2 / 6 + (0 - x[n])^3 / 24 + (0 - x[n])^4 / 120)
32+
(exp(x[1]) - exp(0)) / (x[1] - 0) +
33+
sum((exp(x[j + 1]) - exp(x[j])) / (x[j + 1] - x[j]) for j = 1:(n - 1)) +
34+
(exp(0) - exp(x[n])) / (0 - x[n])
4135
)
4236
)
4337
)

0 commit comments

Comments
 (0)