-
Notifications
You must be signed in to change notification settings - Fork 0
/
golden_search.py
64 lines (52 loc) · 1.26 KB
/
golden_search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""
search for the minimum of a function in a
variable with the golden-section search method
"""
def golden_search(f, a, b, tol):
"""
Parameters
----------
f : callable
function to find the minimum,
can be f(x)
a : float
first extreme
b : float
second extreme
tol : float
required tollerance
the function stops when all components
of the gradient have smaller than tol
Returns
-------
sol : float
minimum
iter : int
number of iteration
"""
iter = 0
gr = (5**(1/2) + 1)/2
c = b - (b - a)/gr
d = a + (b - a)/gr
while abs(b - a) > tol:
if f(c) < f(d):
b = d
else:
a = c
c = b - (b - a)/gr
d = a + (b - a)/gr
iter += 1
sol = (b + a)/2
return sol, iter
if __name__ == "__main__":
def F(x):
"""
function to find the minimum
local minimun = 0.8375654352833
global minimum = -1.1071598716888
"""
return (x**2 - 1)**2 + x
x_min, iter = golden_search(F, -2, 5, 1e-10)
print(f"Punto di minimo x_min = {x_min:.10f}")
print(f"Valore nel minimo F(x_min) = {F(x_min):.10f}")
print(f"numero di iterazioni = {iter}")