summaryrefslogtreecommitdiff
path: root/math/goldenSectionSearch.cpp
diff options
context:
space:
mode:
authormzuenni <michi.zuendorf@gmail.com>2022-09-28 13:48:16 +0200
committermzuenni <michi.zuendorf@gmail.com>2022-09-28 13:48:16 +0200
commit99259d60cb345eae15211397f3199aa86ac2bceb (patch)
tree437d19c8af9d89d3f60d06b3b34c0749f59d3e69 /math/goldenSectionSearch.cpp
parent153e69c9fd0d2a86518c9f18878023ee872a5c78 (diff)
fix
Diffstat (limited to 'math/goldenSectionSearch.cpp')
-rw-r--r--math/goldenSectionSearch.cpp17
1 files changed, 9 insertions, 8 deletions
diff --git a/math/goldenSectionSearch.cpp b/math/goldenSectionSearch.cpp
index 2be8c2d..20b15e8 100644
--- a/math/goldenSectionSearch.cpp
+++ b/math/goldenSectionSearch.cpp
@@ -1,14 +1,15 @@
ld gss(ld l, ld r, function<ld(ld)> f) {
- ld r = (sqrtl(5.0l)-1)/2;
- ld x1 = b - r*(b-a), x2 = a + r*(b-a);
+ ld inv = (sqrt(5.0l) - 1) / 2;
+ ld x1 = r - inv*(r-l), x2 = l + inv*(r-l);
ld f1 = f(x1), f2 = f(x2);
for (int i = 0; i < 200; i++) {
if (f1 < f2) { //change to > to find maximum
- b = x2; x2 = x1; f2 = f1;
- x1 = b - r*(b-a); f1 = f(x1);
+ u = x2; x2 = x1; f2 = f1;
+ x1 = r - inv*(r-l); f1 = f(x1);
} else {
- a = x1; x1 = x2; f1 = f2;
- x2 = a + r*(b-a); f2 = f(x2);
- }}
- return a;
+ l = x1; x1 = x2; f1 = f2;
+ x2 = l + inv*(r-l); f2 = f(x2);
+ }
+ }
+ return l;
}