Advertisement
overwater

Untitled

Mar 7th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.32 KB | None | 0 0
  1. def min_brent(func, a, b, tol=1e-5, max_iter=500, disp=False, trace=False):
  2.     hist = {'x': [], 'f': [], 'n_evals': []}
  3.     a, c = a, b
  4.     K = (3 - 5 ** 0.5) / 2
  5.     x = w = v = a + K * (c - a)
  6.     fx = fw = fv = func(x)
  7.     hist['n_evals'].append(1)
  8.     d = e = c - a
  9.     I = np.zeros(max_iter + 1)
  10.     I[0] = c - a
  11.     u = 0
  12.     for i in range(max_iter):
  13.         g, e = e, d
  14.         t = tol * abs(x) + tol / 10.
  15.         if abs(x - (a + c) / 2) + (c - a) / 2 <= 2 * t:
  16.             return get_result(hist, 0, trace)
  17.         parabolic_flag = True
  18.         if abs(x - v) > tol and abs(x - w) > tol \
  19.                 and abs(v - w) > tol and abs(fx - fw) > tol \
  20.                 and abs(fx - fv) > tol and abs(fw - fv) > tol:
  21.             u = get_min_parabolas(fx, fv, fw, x, v, w)
  22.             if a <= u <= c and abs(u - x) < g / 2.:
  23.                 if u - a < 2 * t or c - u < 2 * t:
  24.                     u = x - np.sign(x - (a + c) / 2) * t
  25.             else:
  26.                 parabolic_flag = False
  27.         else:
  28.             parabolic_flag = False
  29.         if not parabolic_flag:
  30.             if x < (a + c) / 2:
  31.                 u = x + K * (c - x)
  32.                 e = c - x
  33.             else:
  34.                 u = x - K * (x - a)
  35.                 e = x - a
  36.         if abs(x - u) < t:
  37.             u = x + np.sign(u - x) * t
  38.         d = abs(u - x)
  39.         fu = func(u)
  40.         hist['x'].append(u)
  41.         hist['f'].append(fu)
  42.         if disp:
  43.             if parabolic_flag:
  44.                 print("{0} iteration, interval's length = {1}, function's min = {2}, parabolic".format(*(i + 1, I[i], hist['f'][-1])))
  45.             else:
  46.                 print("{0} iteration, interval's length = {1}, function's min = {2}, golden".format(*(i + 1, I[i], hist['f'][-1])))
  47.         hist['n_evals'].append(hist['n_evals'][-1] + 1)
  48.         if fu <= fx:
  49.             if u >= x:
  50.                 a = x
  51.             else:
  52.                 c = x
  53.             v, w, x, fv, fw, fx = w, x, u, fw, fx, fu
  54.         else:
  55.             if u >= x:
  56.                 c = u
  57.             else:
  58.                 a = u
  59.             if fu <= fw or abs(x - w) <= tol:
  60.                 v, w, fv, fw = w, u, fw, fu
  61.             elif fu <= fv or abs(v - x) <= tol or abs(v - w) <= tol:
  62.                 v, fv = u, fu
  63.         I[i + 1] = c - a
  64.     return get_result(hist, 1, trace)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement