Class: Minimization::GoldenSection

Inherits:
Unidimensional show all
Defined in:
lib/minimization.rb

Overview

Golden Section Minimizer.

Basic minimization algorithm. Slow, but robust. See Unidimensional for methods.

Usage.

require 'minimization'
min=Minimization::GoldenSection.new(-1000,20000  , proc {|x| (x+1)**2}
min.expected=1.5  # Expected value
min.iterate
min.x_minimum
min.f_minimum
min.log

Constant Summary

Constants inherited from Unidimensional

Unidimensional::EPSILON, Unidimensional::MAX_ITERATIONS

Instance Attribute Summary

Attributes inherited from Unidimensional

#epsilon, #expected, #f_minimum, #iterations, #log, #log_header, #x_minimum

Instance Method Summary collapse

Methods inherited from Unidimensional

#f, #initialize, #log_summary, minimize

Constructor Details

This class inherits a constructor from Minimization::Unidimensional

Instance Method Details

#iterateObject

Start the iteration


151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/minimization.rb', line 151

def iterate
  ax=@lower
  bx=@expected
  cx=@upper
  c = (3-Math::sqrt(5)).quo(2);
  r = 1-c;

  x0 = ax;
  x3 = cx;
  if ((cx-bx).abs > (bx-ax).abs)
    x1 = bx;
    x2 = bx + c*(cx-bx);
  else
    x2 = bx;
    x1 = bx - c*(bx-ax);
  end
  f1 = f(x1);
  f2 = f(x2);

  k = 1;



  while (x3-x0).abs > @epsilon and k<@max_iteration
    if f2 < f1
      x0 = x1;
      x1 = x2;
      x2 = r*x1 + c*x3;   # x2 = x1+c*(x3-x1)
      f1 = f2;
      f2 = f(x2);
    else
      x3 = x2;
      x2 = x1;
      x1 = r*x2 + c*x0;   # x1 = x2+c*(x0-x2)
      f2 = f1;
      f1 = f(x1);
    end
    @log << [k, x3,x0, f1,f2,(x3-x0).abs, (f1-f2).abs]

    k +=1;
  end

  if f1 < f2
    @x_minimum = x1;
    @f_minimum = f1;
  else
    @x_minimum = x2;
    @f_minimum = f2;
  end
  true
end