import numpy as np
import matplotlib.pyplot as plt
def bisection_method(f, a, b, tol=1e-6, max_iter=100):
if f(a) * f(b) >= 0:
print(f"Invalid interval: f({a}) = {f(a)}, f({b}) = {f(b)}")
print("Searching for a valid interval...")
step = 0.1
while f(a) * f(b) >= 0 and (b - a) > step:
a -= step
b += step
if f(a) * f(b) >= 0:
raise ValueError("Could not find a valid interval with opposite signs.")
for i in range(max_iter):
c = (a + b) / 2
if abs(f(c)) < tol or (b - a) / 2 < tol:
return c
elif f(c) * f(a) < 0:
b = c
else:
a = c
return c
def newton_raphson(f, df, x0, tol=1e-6, max_iter=100):
for i in range(max_iter):
fx = f(x0)
dfx = df(x0)
if abs(fx) < tol:
return x0
if dfx == 0:
raise ValueError("Derivative is zero. Choose a different starting point.")
x0 = x0 - fx / dfx
return x0
def secant_method(f, x0, x1, tol=1e-6, max_iter=100):
for i in range(max_iter):
f0, f1 = f(x0), f(x1)
if abs(f1) < tol:
return x1
if abs(f1 - f0) < 1e-12: # Avoid division by very small number
raise ValueError("Zero denominator encountered. Choose different initial values.")
x2 = x1 - f1 * (x1 - x0) / (f1 - f0)
if abs(x2 - x1) < tol:
return x2
x0, x1 = x1, x2
return x1
# Define functions for Equation 1: alpha - tan(alpha) = 0
def f1(alpha):
return alpha - np.tan(alpha)
def df1(alpha):
return 1 - (1 / np.cos(alpha))**2
# Solve Equation 1 using different methods
try:
root_bisection = bisection_method(f1, 4, 5)
root_newton = newton_raphson(f1, df1, 4.5)
root_secant = secant_method(f1, 4, 4.5) # Adjusted initial guesses
print(f"Equation 1 Roots:\nBisection: {root_bisection}\nNewton-Raphson: {root_newton}\nSecant: {root_secant}")
except ValueError as e:
print("Error:", e)
# Define functions for Equation 2: sin(alpha) - sqrt(m) * alpha = 0 (m = 0.5)
m = 0.5
def f2(alpha):
return np.sin(alpha) - np.sqrt(m) * alpha
def df2(alpha):
return np.cos(alpha) - np.sqrt(m)
# Solve Equation 2 using different methods
try:
root_bisection_2 = bisection_method(f2, 0, 2)
root_newton_2 = newton_raphson(f2, df2, 1)
root_secant_2 = secant_method(f2, 0.5, 1.5) # Adjusted initial guesses
print(f"Equation 2 Roots:\nBisection: {root_bisection_2}\nNewton-Raphson: {root_newton_2}\nSecant: {root_secant_2}")
except ValueError as e:
print("Error:", e)