Module: GoldenSectionSearch

Defined in:
lib/golden_section_search.rb,
lib/golden_section_search/version.rb

Constant Summary collapse

GOLDEN_RATIO =
(Math.sqrt(5) + 1) / 2
VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.find_maximum(function, left_value, right_value, tolerance = 1.0e-5) ⇒ Object


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/golden_section_search.rb', line 22

def self.find_maximum(function, left_value, right_value, tolerance = 1.0e-5)
  middle_left_value = right_value - (right_value - left_value) / GOLDEN_RATIO
  middle_right_value = left_value + (right_value - left_value) / GOLDEN_RATIO
  while (right_value - left_value).abs > tolerance
    if function.call(middle_left_value) > function.call(middle_right_value)
      right_value = middle_right_value
    else
      left_value = middle_left_value
    end
    middle_left_value = right_value - (right_value - left_value) / GOLDEN_RATIO
    middle_right_value = left_value + (right_value - left_value) / GOLDEN_RATIO
  end

  (left_value + right_value) / 2
end

.find_minimum(function, left_value, right_value, tolerance = 1.0e-5) ⇒ Object


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/golden_section_search.rb', line 6

def self.find_minimum(function, left_value, right_value, tolerance = 1.0e-5)
  middle_left_value = right_value - (right_value - left_value) / GOLDEN_RATIO
  middle_right_value = left_value + (right_value - left_value) / GOLDEN_RATIO
  while (right_value - left_value).abs > tolerance
    if function.call(middle_left_value) < function.call(middle_right_value)
      right_value = middle_right_value
    else
      left_value = middle_left_value
    end
    middle_left_value = right_value - (right_value - left_value) / GOLDEN_RATIO
    middle_right_value = left_value + (right_value - left_value) / GOLDEN_RATIO
  end

  (left_value + right_value) / 2
end