Created
April 16, 2012 13:53
-
-
Save sakjur/2398976 to your computer and use it in GitHub Desktop.
Newton-Raphson
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
def func(x): | |
## Main function. | |
return pow(x, 3) - 7 - 5 * x # Change to suit your needs | |
def derive(x, y=5): | |
## Deriving | |
if 0 <= y <= 10: | |
h = pow(10, -10) | |
deriv = (func(x+h) - func(x)) / h | |
floatpoints = "%." + str(y) + "f" | |
return float(floatpoints % deriv) | |
else: | |
exit("Error:\n y must be between 0 and 10."); | |
def newtonraphson(x, y=5, debug=False): | |
## Implementing the Newton-Raphson method | |
lastnum = x | |
currentnum = None | |
while lastnum != currentnum or currentnum == 0: | |
if currentnum != None: | |
lastnum = currentnum | |
else: | |
lastnum = lastnum | |
i = lastnum | |
currentnum = i - (func(i)/derive(i, y)) | |
if debug == True: | |
print currentnum | |
floatpoints = "%." + str(y) + "f" | |
return float(floatpoints % currentnum) | |
print(newtonraphson(-50, 3, True)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment