Ex-2-code
Ex-2-code
# Newton-Raphson Method
def newton_raphson_method(func_str, df_func_str, x0, tol=0.1, max_iter=100,
true_root=None):
iteration_data = []
ea_values = [] # To store Ea for plotting
iteration_numbers = [] # To store iteration numbers for plotting
x = x0 # Initial guess
for i in range(max_iter):
f_x = evaluate_function(func_str, x)
df_x = evaluate_function(df_func_str, x)
# Print row
print(f"{i:<5}{x:<12.6f}{f_x:<12.6f}{df_x:<12.6f}{f'{ea:.6f}' if ea is not
None else 'N/A':<12}{f'{et:.6f}' if et is not None else 'N/A':<12}")
# Secant Method
def secant_method(func_str, x0, x1, tol=0.1, max_iter=100, true_root=None):
iteration_data = []
ea_values = [] # To store Ea for plotting
iteration_numbers = [] # To store iteration numbers for plotting
x_prev = x0
x_curr = x1 # Initial guesses
for i in range(max_iter):
f_x_prev = evaluate_function(func_str, x_prev)
f_x_curr = evaluate_function(func_str, x_curr)
# Print row
print(f"{i:<5}{x_curr:<12.6f}{f_x_curr:<12.6f}{f'{ea:.6f}' if ea is not
None else 'N/A':<12}{f'{et:.6f}' if et is not None else 'N/A':<12}")
# Main Execution
try:
# Asking user for inputs
func_str = input("Enter the function in terms of x (e.g., 'x**3 - 5*x**2 + 6*x
- 2'): ")
except ValueError:
print("Invalid input. Please enter numerical values.")
except Exception as e:
print(f"An error occurred: {e}")