Approximates all complex roots of a polynomial using the Weierstrass (Durand-Kerner) method. Args: polynomial: A function that takes a NumPy array of complex numbers and returns the polynomial values at those points. degree: Degree of the polynomial (
(
polynomial: Callable[[np.ndarray], np.ndarray],
degree: int,
roots: np.ndarray | None = None,
max_iter: int = 100,
)
| 4 | |
| 5 | |
| 6 | def weierstrass_method( |
| 7 | polynomial: Callable[[np.ndarray], np.ndarray], |
| 8 | degree: int, |
| 9 | roots: np.ndarray | None = None, |
| 10 | max_iter: int = 100, |
| 11 | ) -> np.ndarray: |
| 12 | """ |
| 13 | Approximates all complex roots of a polynomial using the |
| 14 | Weierstrass (Durand-Kerner) method. |
| 15 | Args: |
| 16 | polynomial: A function that takes a NumPy array of complex numbers and returns |
| 17 | the polynomial values at those points. |
| 18 | degree: Degree of the polynomial (number of roots to find). Must be ≥ 1. |
| 19 | roots: Optional initial guess as a NumPy array of complex numbers. |
| 20 | Must have length equal to 'degree'. |
| 21 | If None, perturbed complex roots of unity are used. |
| 22 | max_iter: Number of iterations to perform (default: 100). |
| 23 | |
| 24 | Returns: |
| 25 | np.ndarray: Array of approximated complex roots. |
| 26 | |
| 27 | Raises: |
| 28 | ValueError: If degree < 1, or if initial roots length doesn't match the degree. |
| 29 | |
| 30 | Note: |
| 31 | - Root updates are clipped to prevent numerical overflow. |
| 32 | |
| 33 | Example: |
| 34 | >>> import numpy as np |
| 35 | >>> def check(poly, degree, expected): |
| 36 | ... roots = weierstrass_method(poly, degree) |
| 37 | ... return np.allclose(np.sort(roots), np.sort(expected)) |
| 38 | |
| 39 | >>> check( |
| 40 | ... lambda x: x**2 - 1, |
| 41 | ... 2, |
| 42 | ... np.array([-1, 1])) |
| 43 | True |
| 44 | |
| 45 | >>> check( |
| 46 | ... lambda x: x**3 - 4.5*x**2 + 5.75*x - 1.875, |
| 47 | ... 3, |
| 48 | ... np.array([1.5, 0.5, 2.5]) |
| 49 | ... ) |
| 50 | True |
| 51 | |
| 52 | See Also: |
| 53 | https://en.wikipedia.org/wiki/Durand%E2%80%93Kerner_method |
| 54 | """ |
| 55 | |
| 56 | if degree < 1: |
| 57 | raise ValueError("Degree of the polynomial must be at least 1.") |
| 58 | |
| 59 | if roots is None: |
| 60 | # Use perturbed complex roots of unity as initial guesses |
| 61 | rng = np.random.default_rng() |
| 62 | roots = np.array( |
| 63 | [ |
nothing calls this directly
no outgoing calls
no test coverage detected