Skip to content

Commit a30d9ed

Browse files
authored
feat: ternary search was added
1 parent 147855e commit a30d9ed

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
double ternary_search(const function<double(double)> &func, double low, double high) {
2+
int it = 0;
3+
while (it < 100) { // with 50 iterations it has precision for 1e-9
4+
double diff = (high - low) / 3.0;
5+
double mid1 = low + diff;
6+
double mid2 = high - diff;
7+
8+
double f1 = func(mid1);
9+
double f2 = func(mid2);
10+
11+
if (f1 > f2) // change to < to find the maximum
12+
low = mid1;
13+
else
14+
high = mid2;
15+
it++;
16+
}
17+
return func(low);
18+
}
19+
// Usage:
20+
// double ans = ternary_search(funct1, low, high);
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// This version is slower than the iterations version.
2+
double ternary_search(const function<double(double)> &func, double low, double high) {
3+
double eps = 1e-9;
4+
while (high - low > eps) {
5+
double diff = (high - low) / 3.0;
6+
double mid1 = low + diff;
7+
double mid2 = high - diff;
8+
9+
double f1 = func(mid1);
10+
double f2 = func(mid2);
11+
12+
if (f1 > f2) // change to < to find the maximum
13+
low = mid1;
14+
else
15+
high = mid2;
16+
}
17+
return func(low);
18+
}
19+
// Usage:
20+
// double ans = ternary_search(funct1, low, high);

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy