Untitled
unknown
plain_text
2 months ago
1.4 kB
5
Indexable
import cmath # Define the polynomial function def f(x): return x**4 - 3*x**3 + x**2 + x + 1 # Muller's Method Implementation def muller_method(x0, x1, x2, tol=1e-5, max_iter=100): for i in range(max_iter): # Compute function values f0, f1, f2 = f(x0), f(x1), f(x2) # Compute differences h1, h2 = x1 - x0, x2 - x1 δ1, δ2 = (f1 - f0) / h1, (f2 - f1) / h2 a = (δ2 - δ1) / (h2 + h1) b = a * h2 + δ2 c = f2 # Compute the quadratic formula roots disc = cmath.sqrt(b**2 - 4 * a * c) denom = b + disc if abs(b + disc) > abs(b - disc) else b - disc x3 = x2 - (2 * c) / denom # Next approximation # Check convergence if abs(x3 - x2) < tol: return x3, i + 1 # Return root and iteration count # Shift values for next iteration x0, x1, x2 = x1, x2, x3 return x3, max_iter # Return last computed root if max iterations reached # Define the intervals intervals = [ (-1, 0, 1), # (a) (-0.5, 0, 0.5), # (b) (0.5, 1, 1.5), # (c) (1.5, 2, 2.5) # (d) ] # Compute roots for each interval for idx, (x0, x1, x2) in enumerate(intervals, start=1): root, iterations = muller_method(x0, x1, x2) print(f"Interval {idx}: [{x0}, {x2}]") print(f" Approximate Root: {root:.6f}") print(f" Iterations Required: {iterations}\n")
Editor is loading...
Leave a Comment