Created
September 27, 2017 21:27
-
-
Save eyllanesc/9c10b80dd30eceeb6223a914e1da9270 to your computer and use it in GitHub Desktop.
Solution of: https://stackoverflow.com/questions/46456703/translate-pseudocode-into-python-secant-method/46457259#46457259
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 math import * | |
def f(x: float) -> float: | |
return exp(x) - sin(x) | |
def secant(x0: float, x1: float, f, epsilon: float, delta: float, iter_max: int) -> float: | |
fx0 = f(x0) | |
fx1 = f(x1) | |
print("{0} {1:.20f} {2:.20f}".format(0, x0, fx0)) | |
if iter_max == 0: | |
return 0, x0, fx0 | |
print("{0} {1:.20f} {2:.20f}".format(1, x1, fx1)) | |
if iter_max == 1: | |
return 1, x1, fx1 | |
for k in range(2, iter_max): | |
if abs(fx0) > abs(fx1): | |
tmp = x0 | |
x0 = x1 | |
x1 =tmp | |
tmp = fx0 | |
fx0 = fx1 | |
fx1 = tmp | |
s = (x1 - x0) / (fx1 - fx0) | |
x1 = x0 | |
fx1 = fx0 | |
x0 = x0 - fx0 * s | |
fx0 = f(x0) | |
print("{0} {1:.20f} {2:.20f}".format(k, x0, fx0)) | |
if abs(fx0) < epsilon or abs(x1 - x0) <= delta: | |
break | |
return k, x0, fx0 | |
root = secant(-3.5, -2.5, f, 0.0000000000000000000001, 0.000001, 100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment