import math
""" MICHAEL JOHN DENQUE'S WORKS,
CRDT: ONLINE TOTURIAL & SOURCE
"""
def bisection_method(func, lower, upper, max_iter):
#TABLE
print(f"{'Iter':<5}{'xl':<20}{'xu':<20}{'xr':<20}{'ea%':<25}")
print('-'*70)
for i in range(max_iter):
midpoint = (lower + upper) / 2 # Calculate midpoint/xr
f_mid = func(midpoint) #f(xr)
# Calculate the error/ea
error = abs((midpoint - lower) / midpoint) * 100
# Print the current iteration's results
print(f"{i + 1:<5}{lower:<20.5f}{upper:<20.5f}{midpoint:<20.5f}{error:<15.5f}")
if error <= 0.05: #KANI RAY GI DUNGAG
break
if f_mid == 0:
return midpoint
# Narrow down the interval
if func(lower) * f_mid < 0:
upper = midpoint # Root is in the lower half
else:
lower = midpoint # Root is in the upper half
return (lower + upper) / 2 # Return the best estimate after max iterations
# Example usage
if __name__ == "__main__":
# Input function as a string
while True:
func_input = input("Enter the function of x or 'q' to quit: ")
if func_input.lower() == 'q':
print("\n OKAY BYEE!!!")
break
else:
# Define the function using eval
def func(x):
return eval(func_input)
# Input lower and upper limits
lower = float(input("Enter the lower limit: "))
upper = float(input("Enter the upper limit: "))
# Input maximum iterations
max_iterations = int(input("Enter the maximum number of iterations: "))
try:
root = bisection_method(func, lower, upper, max_iterations)
print(f"\nThe root is approximately: {root:.5f}")
except ValueError as e:
print(e)