import math import re def prepare_expression(expr): """Add explicit multiplication for terms like '3x' -> '3*x'.""" expr = re.sub(r'(\d)(x)', r'\1*\2', expr) return expr def eval_expression(expr, x): """Evaluate f(x) for the given expression string.""" prepared_expr = prepare_expression(expr) local_namespace = { "x": x, "sin": math.sin, "cos": math.cos, "tan": math.tan, "exp": math.exp, "sqrt": math.sqrt, "log": math.log, "pi": math.pi } return eval(prepared_expr, {"__builtins__": {}}, local_namespace) def arc_length_approx(f_str, a, b, n): """ Approximate the arc length of y = f(x) from x=a to x=b using n straight-line (Pythagorean) segments. """ h = (b - a) / n x_values = [a + i * h for i in range(n + 1)] y_values = [eval_expression(f_str, xv) for xv in x_values] total_length = 0 for i in range(n): dx = x_values[i + 1] - x_values[i] dy = y_values[i + 1] - y_values[i] segment_length = math.sqrt(dx**2 + dy**2) # Pythagorean theorem total_length += segment_length return total_length # User prompts print("Arc Length Approximation Program") f_str = input("1. Enter the function f(x): ") a = float(input("2. Enter the starting x-value: ")) b = float(input("3. Enter the ending x-value: ")) n = int(input("4. Enter the number of steps (n): ")) length = arc_length_approx(f_str, a, b, n) print(f"\nApproximate arc length using {n} segments: {length:.6f}")