Skip to content

Instantly share code, notes, and snippets.

@sakjur
Created April 16, 2012 13:53
Show Gist options
  • Save sakjur/2398976 to your computer and use it in GitHub Desktop.
Save sakjur/2398976 to your computer and use it in GitHub Desktop.
Newton-Raphson
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