Created
August 16, 2018 18:31
-
-
Save 19007361/476400ca95fb53be6b90d1ec79b67c05 to your computer and use it in GitHub Desktop.
secant.py
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 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