Last active
November 19, 2020 16:04
-
-
Save danielz02/33cd7a3be35fa68503b659a32dcb33fd to your computer and use it in GitHub Desktop.
ND/1D Root Finding
This file contains hidden or 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 | |
| roots = [] | |
| for a, b in intervals: | |
| if function(a) * function(b) > 0 or a >= b: | |
| roots.append(None) | |
| continue | |
| m = None | |
| for i in range(n_iter): | |
| fa = function(a) | |
| fb = function(b) | |
| m = (a + b) / 2 | |
| fm = function(m) | |
| if np.abs(fm) < epsilon: | |
| break | |
| a = m if fm * fa > 0 else a | |
| b = m if fm * fb > 0 else b | |
| roots.append(m) | |
| print(roots) |
This file contains hidden or 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 numpy.linalg as la | |
| x_0 = 2.9 | |
| tol = 1e-7 | |
| f = lambda x: np.sin(x) * x | |
| df = lambda x: np.sin(x) + np.cos(x) * x | |
| count = 0 | |
| fx = f(x_0) | |
| dfx = df(x_0) | |
| xi = x_0 - fx / dfx | |
| while np.abs(fx - 0) >= tol: | |
| fx = f(xi) | |
| dfx = df(xi) | |
| xi = xi - fx / dfx | |
| count += 1 | |
| print(count) | |
This file contains hidden or 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 numpy.linalg as la | |
| # TODO: Change us!! | |
| x_i= None | |
| f = lambda x, y: array([x ** 3 - y ** 2, x + y * x ** 2 - 2]) | |
| J = lambda x, y: np.array([[3 * (x ** 2), -2 * y], [1 + 2 * x * y, x ** 2]]) | |
| count = 0 | |
| x_0, y_0 = xi | |
| fx = f(x_0, y_0) | |
| j = J(x_0, y_0) | |
| xi = xi + la.solve(j, -fx) | |
| while la.norm(fx, 2) >= tol: | |
| x, y = xi | |
| fx = f(x, y) | |
| j = J(x, y) | |
| xi = xi + la.solve(j, -fx) | |
| count += 1 | |
| root = xi | |
| res = la.norm(fx, 2) |
This file contains hidden or 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 | |
| roots = [] | |
| xks = xks.tolist() | |
| for i in range(2, 7): | |
| df_k = (f(xks[i - 1]) - f(xks[i - 2])) / (xks[i - 1] - xks[i - 2]) | |
| x_next = xks[i - 1] - f(xks[i - 1]) / df_k | |
| xks.append(x_next) | |
| roots.append(x_next) | |
| roots = np.array(roots) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment