Created
January 3, 2014 12:29
-
-
Save metula/8237180 to your computer and use it in GitHub Desktop.
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
| from random import * | |
| def NR(func, deriv, epsilon=10**(-8),n=100,x0=None): | |
| """ Given a real valued func and its real value derivative, | |
| deriv, NR attempts to find a zero of func, using the | |
| Newton-Raphson method. | |
| NR starts with a an initial x0 (default value is None | |
| which is replaced upon execusion by a random number distributed | |
| uniformly in (-100.,100.)), and performs n=100 iterations. | |
| If the absolute value derivative on some x_i is smaller | |
| than epsilon, None is the returned value. """ | |
| if x0 is None: | |
| x0 = uniform(-100.,100.) | |
| x = x0 | |
| y = func(x) | |
| for i in range(n): | |
| if abs(y) < epsilon: | |
| return x | |
| elif abs(deriv(x)) < epsilon: | |
| print ("zero derivative, x0=", x0, " i=", i, " xi=", x) | |
| return None | |
| else: | |
| x = x - func(x) / deriv(x) | |
| y = func(x) | |
| print("no convergence, x0=", x0," i=", i, " xi=", x) | |
| return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment