区間2分法と1変数方程式

区間 [left, right] で、関数 f は必ず単調増加あるいは単調減少でなければならない。

def binary_search(f, left, right)
  up_down = (f[right] > f[left]) ? 1 : -1 
  while (left - right).abs > 0.000000000000001
    a = (left + right) / 2.0
    if f[a] * up_down > 0
      right = a
    else
      left = a
    end
  end
  left
end

f = proc do |x|
  x ** (1 / x - 4) * ((Math.log(x) - 1) ** 2 - 3 * x + 2 * x * Math.log(x))
end

puts binary_search(f, 0.5, 1)    #=>0.5819327056085921
puts binary_search(f, 1, 10)     #=>4.3677709670560185

1変数方程式を数値計算で解く(Ruby) - Camera Obscura