import math __author__ denis f_global lambda _x math exp _x a_global b

 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
import math
__author__ = 'denis'
f_global = lambda _x: math.exp(_x)
a_global = 0
b_global = 3
phi = (1 + math.sqrt(5)) / 2
e = 0.01
def find_min_gold(f, a, b):
while math.fabs(b - a) > e:
x1, x2 = b - (b - a) / phi, a + (b - a) / phi
y1, y2 = f(x1), f(x2)
if y1 >= y2:
a = x1
else:
b = x2
return (a + b) / 2
def find_min_half(f, a, b):
while (math.fabs(b - a)) > e:
half_x1 = ((a + b)/2 - e/4)
half_x2 = ((a + b)/2 + e/4)
if f(half_x1) <= f(half_x2):
b = half_x2
else:
a = half_x1
return (a + b) / 2
minimum1 = find_min_gold(f_global, a_global, b_global)
minimum2 = find_min_half(f_global, a_global, b_global)
print('Minimum of function on [' + str(a_global) + ', ' + str(b_global) + '] is ' + str(f_global(minimum1)) + '')
print('Minimum of function on [' + str(a_global) + ', ' + str(b_global) + '] is ' + str(f_global(minimum2)))