Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@19007361
Created August 16, 2018 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 19007361/476400ca95fb53be6b90d1ec79b67c05 to your computer and use it in GitHub Desktop.
Save 19007361/476400ca95fb53be6b90d1ec79b67c05 to your computer and use it in GitHub Desktop.
secant.py
def secant(f, a, b, tol=1e-9, n=100):
fmt = "{:2} {:>13.10f} {:>13.10f} {:>13.10f}"
p1, p2 = float(a), float(b)
i = 1
print fmt.format(1, p1, p2, f(p2))
while abs(p1 - p2) > tol and i <= n:
p1, p2 = p2, p2 - (f(p2) * (p2 - p1)) / (f(p2) - f(p1))
i += 1
print fmt.format(i, p1, p2, f(p2))
return p2
def f(x):
return x**3 + 4*x**3 - 10
if __name__ == "__main__":
r1 = secant(f, 1, 2)
print "root = {:.10f}".format(r1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment