import numpy as np import matplotlib pyplot as plt import math as np a

 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
import numpy as np
import matplotlib.pyplot as plt
import math as m
x = np.array([0.78,1.56,2.34,3.12,3.9])
y = np.array([2.5,1.2,1.12,2.25,4.28])
eps = 1.e-3
def P(x,y,x0):
summ = i = j = 0
def coeffs(x, y ,n1, n2):
if(n2-n1 == 0):
return y[n2]
return (coeffs(x,y,n1+1,n2) - coeffs(x,y,n1,n2-1))/(x[n2]-x[n1])
summ = coeffs(x,y, 0, 0)
s = 1
for i in range(1, len(x)):
s *= (x0-x[i-1])
summ += coeffs(x,y,0,i)*s
return summ
x0 = np.arange(x[0],x[-1],1.e-5)
y0 = P(x,y,x0);
g0 = x0**3 + y0
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
def Golden_section_search(x,y, eps):
tao = 0.5*(m.sqrt(5)-1)
x_l = x[0]
x_r = x[-1]
x_1 = x_l + (1-tao)*(x_r - x_l)
x_2 = x_l + tao*(x_r - x_l)
i = 0
while ((tao)**i)*abs(x_l - x_r) > eps:
i += 1
x_1 = x_l + (1-tao)*(x_r - x_l)
x_2 = x_l + tao*(x_r - x_l)
x_1 = find_nearest(x,x_1)
x_2 = find_nearest(x,x_2)
if y[np.where(x==x_1)] < y[np.where(x==x_2)]:
x_r = x_2
else:
x_l = x_1
if y[np.where(x==x_1)] < y[np.where(x==x_2)]:
return x_1
else:
return x_2
Golden_section_search(x0,g0, eps)