0% found this document useful (0 votes)
12 views2 pages

Python-Exp4-Semester7.ipynb - Colab

Uploaded by

Status king
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

Python-Exp4-Semester7.ipynb - Colab

Uploaded by

Status king
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

10/09/2024, 22:01 python-exp4-semester7.

ipynb - Colab

def secant_method(func, x0, x1, tol=1e-6, max_iter=100):


"""
Implements the Secant method to find the root of a function.

Parameters:
- func: The target function.
- x0: Initial guess for the root.
- x1: Another initial guess for the root.
- tol: Tolerance for stopping criterion (default is 1e-6).
- max_iter: Maximum number of iterations (default is 100).

Returns:
- root: Approximation of the root.
- iterations: Number of iterations performed.
"""

x_k_minus_1 = x0
x_k = x1

for k in range(max_iter):
f_k_minus_1 = func(x_k_minus_1)
f_k = func(x_k)

# Compute the next approximation


x_k_plus_1 = x_k - f_k * (x_k - x_k_minus_1) / (f_k - f_k_minus_1)

# Check for convergence


if abs(x_k_plus_1 - x_k) < tol:
return x_k_plus_1, k + 1 # Return the root and the number of iterations

x_k_minus_1 = x_k
x_k = x_k_plus_1

raise ValueError("Secant method did not converge within the maximum number of iterations.")

# Example usage
def target_function(x):
return x**2 - 4 # Function to find the square root of 4 (i.e., x^2 - 4 = 0)

# Initial guesses
x0 = 1.0
x1 = 3.0

# Call the Secant method function


root, iterations = secant_method(target_function, x0, x1)

print(f"Root found: {root}")


print(f"Iterations: {iterations}")

Root found: 2.0000000000004996


Iterations: 6

https://colab.research.google.com/drive/1SWnipWoTj5DCo9dsNRAvyQKX7uaBtV_u#printMode=true 1/2
10/09/2024, 22:01 python-exp4-semester7.ipynb - Colab

https://colab.research.google.com/drive/1SWnipWoTj5DCo9dsNRAvyQKX7uaBtV_u#printMode=true 2/2

You might also like