Created
March 24, 2017 09:33
-
-
Save mberlanda/1abd60d11963a775cb16e6013f71f734 to your computer and use it in GitHub Desktop.
Ruby implementation of the Newton's method (https://en.wikipedia.org/wiki/Newton%27s_method)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NewtonsMethod | |
def initialize(f_proc, f_prime_proc) | |
@fp = f_proc | |
@fpp = f_prime_proc | |
end | |
def apply(x) | |
x - (@fp.call(x) / (@fpp.call(x) * 1.0)) | |
end | |
def solve(x, steps) | |
x1 = apply(x) | |
r = @fp.call(x1) | |
s = steps - 1 | |
return x1 unless s > 0 || r.zero? | |
solve(x1, s) | |
end | |
end | |
f = ->(x) { -4 * (x**3) - 2 * (x**2) - 2 * x - 3 } | |
fp = ->(x) { -12 * (x**2) - 4 * x - 2 } | |
nm = NewtonsMethod.new(f, fp) | |
nm.solve(-2, 2) | |
# => -1.0582629570422042 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment