-
Notifications
You must be signed in to change notification settings - Fork 0
/
sec10.2.py
95 lines (71 loc) · 2.39 KB
/
sec10.2.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import numpy as np
from numpy import linalg
from abc import abstractmethod
import pandas as pd
import math
pd.options.display.float_format = '{:,.10f}'.format
np.set_printoptions(suppress=True, precision=10)
TOR = pow(10.0, -5)
class NewtonMethod(object):
def __init__(self):
return
@abstractmethod
def f(self, x):
return NotImplementedError('Implement f()!')
@abstractmethod
def jacobian(self, x):
return NotImplementedError('Implement jacobian()!')
@abstractmethod
def run(self, x):
return NotImplementedError('Implement run()!')
class Newton(NewtonMethod):
def __init__(self):
super(NewtonMethod, self).__init__()
def f(self, x):
sol = np.zeros(len(x))
sol[0] = 3 * x[0] - math.cos(x[1] * x[2]) - 1.0 / 2.0
sol[1] = pow(x[0], 2) - 81 * pow(x[1] + 0.1, 2) + math.sin(x[2]) + 1.06
sol[2] = math.exp(-x[0] * x[1]) + 20 * x[2] + (10 * math.pi - 3.0) / 3.0
return sol
def jacobian(self, x):
jac = np.zeros(shape=(3, 3))
jac[0][0] = 3.0
jac[0][1] = x[2] * math.sin(x[1] * x[2])
jac[0][2] = x[1] * math.sin(x[1] * x[2])
jac[1][0] = 2 * x[0]
jac[1][1] = -162 * (x[1] + 0.1)
jac[1][2] = math.cos(x[2])
jac[2][0] = -x[1] * math.exp(-x[0] * x[1])
jac[2][1] = -x[0] * math.exp(-x[0] * x[1])
jac[2][2] = 20
return jac
def run(self, x):
"""
given x_0 in R^3 as a starting point.
:param x: x_0 as described
:return: the minimizer x* of f
"""
df = pd.DataFrame(columns=['x' + str(i + 1) for i in range(len(x))] + ['residual', 'actual-residual'])
row = len(df)
df.loc[row] = [xe for xe in x] + [np.nan, np.nan]
while True:
jac = self.jacobian(x)
f = -self.f(x)
y = linalg.solve(jac, f)
nx = x + y
residual = linalg.norm(x - nx, np.inf)
x = nx
row = len(df)
df.loc[row] = [nxe for nxe in nx] + [residual, np.nan]
if residual < TOR:
break
for i in range(len(df)):
xk = np.array([df.loc[i][j] for j in range(len(x))])
df.loc[i][4] = linalg.norm(x - xk, np.inf)
print(df)
def main():
x0 = np.array([0.1, 0.1, -0.1])
Newton().run(x0)
return
if __name__ == '__main__':
main()