'''A, B = bracket (f, xStart, h) Finds the brackets (a, B) of a minimum point of User-supplied scalar function f (x ). The search starts downhill from xStart with a step Length h. X, fMin = search (f, a, B, tol = 1.0e-6) Golden section method for determining x that minimizes The user-supplied scalar function f (x ). The minimum must be bracketed in (a, B ). ''' From math import log, ceil Def bracket (f, x1, h ): C = 1.618033989. F1 = f (x1) X2 = x1 + h; f2 = f (x2) # Determine downhill direction and change sign of h if needed If f2> f1: H =-h X2 = x1 + h; f2 = f (x2) # Check if minimum between x1-h and x1 + h If f2> f1: return x2, x1-h # Search loop For I in range (100 ): H = c * h X3 = x2 + h; f3 = f (x3) If f3> f2: return x1, x3 X1 = x2; x2 = x3 F1 = f2; f2 = f3 Print "Bracket did not find a mimimum" Def search (f, a, B, tol = 1.0e-9 ): NIter = int (ceil (-2.078087 * log (tol/abs (B-a) # Eq. (10.4) R = 0.618033989. C = 1.0-R # First telescoping X1 = R * a + C * B; x2 = C * a + R * B F1 = f (x1); f2 = f (x2) # Main loop For I in range (nIter ): If f1> f2: A = x1 X1 = x2; f1 = f2 X2 = C * a + R * B; f2 = f (x2) Else: B = x2 X2 = x1; f2 = f1 X1 = R * a + C * B; f1 = f (x1) If f1 <f2: return x1, f1 Else: return x2, f2 |