The secant method is used to find the root of an equation f(x) = 0. It is started from two distinct estimates x1 and x2 for the root. It is an iterative procedure involving linear interpolation to a root. The iteration stops if the difference between two intermediate values is less than convergence factor.
Input : equation = x3 + x - 1 x1 = 0, x2 = 1, E = 0.0001 Output : Root of the given equation = 0.682326 No. of iteration=5
Initialize: x1, x2, E, n // E = convergence indicator calculate f(x1),f(x2) if(f(x1) * f(x2) = E); //repeat the loop until the convergence print 'x0' //value of the root print 'n' //number of iteration } else print "can not found a root in the given interval"
# Python3 Program to find root of an
# equations using secant method
# function takes value of x
# and returns f(x)
# we are taking equation
# as x^3+x-1
f = pow(x, 3) + x – 1;
def secant(x1, x2, E):
n = 0; xm = 0; x0 = 0; c = 0;
if (f(x1) * f(x2) < 0): while True: # calculate the intermediate value x0 = ((x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1))); # check if x0 is root of # equation or not c = f(x1) * f(x0); # update the value of interval x1 = x2; x2 = x0; # update number of iteration n += 1; # if x0 is the root of equation # then break the loop if (c == 0): break; xm = ((x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1))); if(abs(xm - x0) < E): break; print("Root of the given equation =", round(x0, 6)); print("No. of iterations = ", n); else: print("Can not find a root in ", "the given inteval"); # Driver code # initializing the values x1 = 0; x2 = 1; E = 0.0001; secant(x1, x2, E); # This code is contributed by mits [tabby title="C#"]
Root of the given equation = 0.682326 No. of iterations = 5
Time Complexity = O(1)
This article is contributed by Niteesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Write a program to calculate pow(x,n)
- Write a program to reverse digits of a number
- Program to find whether a no is power of two
- Write an Efficient Method to Check if a Number is Multiple of 3
- Program to find parity
- Write an Efficient C Program to Reverse Bits of a Number
- Write a program to print all permutations of a given string
- Write a program to add two numbers in base 14
- Babylonian method for square root
- Find minimum number to be divided to make a number a perfect square
- Find whether a given number is a power of 4 or not
- Find Union and Intersection of two unsorted arrays
- Program for Fibonacci numbers
- To find sum of two numbers without using any operator
- Find day of the week for a given date