Class: RootSolver::Newton
- Inherits:
-
Object
- Object
- RootSolver::Newton
- Defined in:
- lib/root_solver.rb
Instance Method Summary collapse
-
#initialize(f, x0 = 0, tol = 0.01, n = 10, eps = 0.001) ⇒ Newton
constructor
A new instance of Newton.
- #solve(f = @f, x0 = @x0, tol = @tol, n = @n, eps = @eps) ⇒ Object
Constructor Details
#initialize(f, x0 = 0, tol = 0.01, n = 10, eps = 0.001) ⇒ Newton
Returns a new instance of Newton.
5 6 7 8 9 10 11 |
# File 'lib/root_solver.rb', line 5 def initialize(f, x0 = 0, tol = 0.01, n = 10, eps = 0.001) @f = f @x0 = x0 @tol = tol @n = n @eps = eps end |
Instance Method Details
#solve(f = @f, x0 = @x0, tol = @tol, n = @n, eps = @eps) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/root_solver.rb', line 13 def solve(f = @f, x0 = @x0, tol = @tol, n = @n, eps = @eps) y0 = f.call(x0) y_prime = (f.call(x0 + eps) - y0) / eps raise NonconvergenceError.new if y_prime.abs < tol x = x0 - y0 / y_prime y = f.call(x) if y.abs < tol #successfully found root x elsif n <= 0 #solver not within threshold after n iterations. x else solve(f, x, tol, n - 1, eps) end end |