Last active
February 21, 2021 21:21
-
-
Save samsonq/9b05531bbbd1d6735175ab08368e0ba5 to your computer and use it in GitHub Desktop.
Newton's 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
import numpy as np | |
import sympy as sym | |
import math | |
class NewtonsMethod: | |
""" | |
Newton's Method to find zeros and optimize functions. | |
""" | |
def __init__(self, f): | |
self.x = sym.Symbol("x") | |
self.f = f | |
def zeros(self, value): | |
""" | |
Recursively performs Newton's Method with initial guess to find zeros. | |
:param value: initial guess | |
""" | |
if math.isclose(self.f(value), 0): | |
return value | |
df = sym.lambdify(self.x, sym.diff(self.f, self.x)) | |
next_value -= self.f(value)/df(value) | |
return self.zeros(self.f, next_value) | |
def optimize(self, value, max_iter=100): | |
""" | |
Performs Newton's Method with initial guess to optimize function. | |
:param value: initial guess | |
""" | |
for _ in range(max_iter): | |
df = sym.lambdify(self.x, sym.diff(self.f, self.x)) | |
d2f = sym.lambdify(self.x, sym.diff(df, self.x)) | |
value -= df(value)/d2f(value) | |
return value | |
if __name__ == "__main__": | |
function = x**2 - 9 | |
newtons = NewtonsMethod(function) | |
guess = 4 | |
optimized = newtons.optimize(function, guess) | |
print(optimized) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment