수학/수치해석

[수치해석] Golden Section Method 파이썬

ntne 2022. 12. 9. 23:24
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
import math
 
def golden(xlow, xhigh, maxit, es):
  iter = 1
  r = (5**0.5 -1)/2
  xl = xlow
  xu = xhigh
  d = r * (xu - xl)
  x1 = xl + d
  x2 = xu - d
  f1 = f(x1)
  f2 = f(x2)
 
  print(" i    xl    fxl    x2     f(x2)    x1    f(x1)   xu    f(xu)   d       ")
  print("%2d %.4f  %.4f %.4f %.4f %.4f %.4f %.4f  %.4f %.4f" % (iter, xl, f(xl), x2, f2, x1, f1, xu, f(xu), d))
  # Suppose We're finding maximum
  if f1 > f2:
    xopt = x1
    fx = f1
  else:
    xopt = x2
    fx = f2
 
  while True:
    d = r*d
    xint = xu - xl
 
    # min 구하면 부등호 < 로 바꾸기    
    if f1 > f2:
      xl = x2
      x2 = x1
      x1 = xl + d
      f2 = f1
      f1 = f(x1)
    else:
      xu = x1
      x1 = x2
      x2 = xu - d
      f1 = f2
      f2 = f(x2)
 
    iter += 1
    
    # min 구하면 부등호 < 로 바꾸기
    if f1 > f2:
      xopt = x1
 
 
    ea = (1-r)*abs((xu-xl)/xopt)*0.01
 
    print("%2d %.4f  %.4f %.4f %.4f %.4f %.4f %.4f  %.4f %.4f" % (iter, xl, f(xl), x2, f2, x1, f1, xu, f(xu), d))
 
    if iter >= maxit or ea <= es:
      print("%.4f is optimal" % xopt)
      break
 
 
def f(x):
  # Min = 3: 
  # return (x**2) -  (6*x) + 15
  # Max = 1.4274
  return 2*math.sin(x) - (x**2)/10
 
golden(0,4,1000,0.00001)
cs