Skip to content

Instantly share code, notes, and snippets.

@AnuragAnalog
Created July 19, 2021 02:29
Show Gist options
  • Save AnuragAnalog/2d5c8d848cd2704e369e8ec7271541a9 to your computer and use it in GitHub Desktop.
Save AnuragAnalog/2d5c8d848cd2704e369e8ec7271541a9 to your computer and use it in GitHub Desktop.
Secant Method Implementation in Python
#!/usr/bin/python3.6
# This method is quite similar to that of the Regula-Falsi method except for the
# condition f(x1).f(x2) < 0. Here the graph of the function y = f(x) in the
# neighborhood of the root is approximated by a secant line or chords. Further,
# the interval at each iteration may not contain the root.
# Let the limits of interval initially be x0 and x1.
# Then the first approximation is given by:
# x2 = x1 – [(x1-x0)/f(x1)-f(x0)]f(x1)
# Again, the formula for successive approximation in general form is
# x(n+1) = xn - [xn - x(n-1)/f(xn)-f(x(n-1))]f(xn)
import math
def f(x):
fx = 3*x**2-15*x+7
return fx
def secant(a, b):
while True:
fa = f(a)
fb = f(b)
root = (a*fb-b*fa)/(fb-fa)
tmp1 = round(b, 9)
tmp2 = round(root, 9)
if tmp1 == tmp2:
print("The root of the given equation is %f"% root)
return
a = b
b = root
a = float(input("Enter the first root: "))
b = float(input("Enter the second root: "))
secant(a, b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment