Class: RootSolver::Bisection
- Inherits:
-
Object
- Object
- RootSolver::Bisection
- Defined in:
- lib/root_solver.rb
Instance Method Summary collapse
-
#initialize(f, low, high, tol = 0.01, n = 10) ⇒ Bisection
constructor
A new instance of Bisection.
- #solve(f = @f, low = @low, high = @high, tol = @tol, n = @n) ⇒ Object
Constructor Details
#initialize(f, low, high, tol = 0.01, n = 10) ⇒ Bisection
Returns a new instance of Bisection.
33 34 35 36 37 38 39 |
# File 'lib/root_solver.rb', line 33 def initialize(f, low, high, tol = 0.01, n = 10) @f = f @tol = tol @n = n @high = high @low = low end |
Instance Method Details
#solve(f = @f, low = @low, high = @high, tol = @tol, n = @n) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/root_solver.rb', line 41 def solve(f = @f, low = @low, high = @high, tol = @tol, n = @n) x = (high + low) / 2 y = f.call(x) if y.abs < tol #successfully found root x elsif n <= 0 #break out of solver after so many iterations x elsif x_converge?(low, high, tol) && !crossing?(f, low, high) raise NoRootError.new else #narrow window of searching by half if y > 0 high = x else low = x end solve(f, low, high, tol, n - 1) end end |