implicit_relaxation.jl
· 1.0 KiB · Julia
Ham
using McCormick, BenchmarkTools
"""
Direct relaxation of implicit function
"""
function direct_relax(f, x, p)
delta = Inf
while delta > 1e-8
x_prev = x
x = f(x, p)
delta = abs(x_prev.cv - x.cv) + abs(x_prev.cc - x.cc)
end
return x
end
"""
Faster alternative
"""
function fast_direct_relax(f, x, p)
delta = Inf
while delta > 1e-8
x_prev = x
x_m = x.cv + .5 * (x.cc - x.cv)
x = f(x_m, p)
delta = abs(x_prev.cv - x.cv) + abs(x_prev.cc - x.cc)
end
return x
end
f(x, p) = (p - (p^3)/6 + (p^5)/120)*x^(-1/2) + 100
p = MC{1,NS}(1.0, 1.0, Interval(0.5, 5.0))
x = MC{1,NS}(1.0, 1.0)
res = @btime direct_relax(f, x, p)
println(res) # 342.860 μs (2414 allocations: 96.52 KiB) MC{1, NS}(99.8362536820914, 100.40188539116205, [97.9454, 103.135], [0.0], [0.0], true)
res = @btime fast_direct_relax(f, x, p)
println(res) # 2.972 μs (301 allocations: 4.75 KiB) MC{1, NS}(99.8675794497822, 100.37248484959062, [97.9679, 103.101], [0.0], [0.0], true)
| 1 | using McCormick, BenchmarkTools |
| 2 | |
| 3 | """ |
| 4 | Direct relaxation of implicit function |
| 5 | """ |
| 6 | function direct_relax(f, x, p) |
| 7 | delta = Inf |
| 8 | while delta > 1e-8 |
| 9 | x_prev = x |
| 10 | x = f(x, p) |
| 11 | delta = abs(x_prev.cv - x.cv) + abs(x_prev.cc - x.cc) |
| 12 | end |
| 13 | |
| 14 | return x |
| 15 | end |
| 16 | |
| 17 | """ |
| 18 | Faster alternative |
| 19 | """ |
| 20 | function fast_direct_relax(f, x, p) |
| 21 | delta = Inf |
| 22 | while delta > 1e-8 |
| 23 | x_prev = x |
| 24 | x_m = x.cv + .5 * (x.cc - x.cv) |
| 25 | x = f(x_m, p) |
| 26 | delta = abs(x_prev.cv - x.cv) + abs(x_prev.cc - x.cc) |
| 27 | end |
| 28 | |
| 29 | return x |
| 30 | end |
| 31 | |
| 32 | f(x, p) = (p - (p^3)/6 + (p^5)/120)*x^(-1/2) + 100 |
| 33 | |
| 34 | p = MC{1,NS}(1.0, 1.0, Interval(0.5, 5.0)) |
| 35 | x = MC{1,NS}(1.0, 1.0) |
| 36 | |
| 37 | res = @btime direct_relax(f, x, p) |
| 38 | println(res) # 342.860 μs (2414 allocations: 96.52 KiB) MC{1, NS}(99.8362536820914, 100.40188539116205, [97.9454, 103.135], [0.0], [0.0], true) |
| 39 | |
| 40 | res = @btime fast_direct_relax(f, x, p) |
| 41 | println(res) # 2.972 μs (301 allocations: 4.75 KiB) MC{1, NS}(99.8675794497822, 100.37248484959062, [97.9679, 103.101], [0.0], [0.0], true) |