1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
| """使用牛顿迭代绘制多项式在复平面上的吸引域。"""
import matplotlib.pyplot as plt import numpy as np
PALETTE = np.array( [ [255, 0, 82], [255, 212, 0], [0, 198, 141], [100, 80, 255], [255, 140, 0], [0, 180, 255], [230, 80, 200], [160, 220, 60], ], dtype=float, ) / 255.0
CONFIG = { "function": lambda z: z**3 - 1, "derivative": lambda z: 3 * z**2, "roots": np.exp(2j * np.pi * np.arange(3) / 3), "title": r"$p(z)=z^3-1$", "xlim": (-2.0, 2.0), "ylim": (-2.0, 2.0), "width": 1800, "height": 1800, "max_iter": 150, "tolerance": 1e-8, "derivative_epsilon": 1e-14, "divergence_limit": 1e10, "darkest_brightness": 0.30, "palette": PALETTE, "figure_size": (9.0, 9.0), "display_dpi": 120, "save_dpi": 300, "interpolation": "nearest", "show_axes": True, "show_title": True, "figure_path": "newton-fractal.png", "raw_path": None, "show": True, }
def compute_newton_fractal(config=None): """计算每个像素收敛到的根、迭代次数和 RGB 图像。""" cfg = CONFIG.copy() if config: cfg.update(config)
function = cfg["function"] derivative_function = cfg["derivative"] roots = np.asarray(cfg["roots"], dtype=np.complex128) if not callable(function) or not callable(derivative_function): raise TypeError("function 和 derivative 必须是可调用对象") if roots.ndim != 1 or len(roots) == 0 or not np.isfinite(roots).all(): raise ValueError("roots 必须是一维、非空且只包含有限复数") width = int(cfg["width"]) height = int(cfg["height"]) x = np.linspace(*cfg["xlim"], width) y = np.linspace(*cfg["ylim"], height) z = x[None, :] + 1j * y[:, None]
root_index = np.full(z.shape, -1, dtype=np.int16) iteration_count = np.full(z.shape, cfg["max_iter"], dtype=np.int16) active = np.ones(z.shape, dtype=bool) tolerance_sq = cfg["tolerance"] ** 2
for iteration in range(cfg["max_iter"] + 1): nearest = np.zeros(z.shape, dtype=np.int16) minimum_distance_sq = np.full(z.shape, np.inf) for index, root in enumerate(roots): distance_sq = (z.real - root.real) ** 2 + (z.imag - root.imag) ** 2 closer = distance_sq < minimum_distance_sq minimum_distance_sq[closer] = distance_sq[closer] nearest[closer] = index
converged = active & (minimum_distance_sq < tolerance_sq) root_index[converged] = nearest[converged] iteration_count[converged] = iteration active[converged] = False
if iteration == cfg["max_iter"] or not active.any(): break
derivative = derivative_function(z) safe = active & np.isfinite(derivative) & ( np.abs(derivative) > cfg["derivative_epsilon"] ) with np.errstate(over="ignore", divide="ignore", invalid="ignore"): z[safe] -= function(z[safe]) / derivative[safe]
failed = active & ( ~np.isfinite(z) | (np.abs(z) > cfg["divergence_limit"]) | ~safe ) active[failed] = False
palette = np.asarray(cfg["palette"], dtype=float) if len(palette) < len(roots): raise ValueError("palette 中的颜色数量不能少于多项式的根数")
image = np.zeros((*z.shape, 3), dtype=float) known = root_index >= 0 level = np.log1p(iteration_count[known]) / np.log1p(cfg["max_iter"]) brightness = 1 - (1 - cfg["darkest_brightness"]) * np.minimum(level, 1) image[known] = palette[root_index[known]] * brightness[:, None] return image, roots, root_index, iteration_count
def demo(config): """按照配置字典绘制、保存并返回牛顿分形。""" cfg = CONFIG.copy() cfg.update(config)
image, roots, root_index, iteration_count = compute_newton_fractal(cfg) fig, ax = plt.subplots( figsize=cfg["figure_size"], dpi=cfg["display_dpi"], ) ax.imshow( image, extent=(*cfg["xlim"], *cfg["ylim"]), origin="lower", interpolation=cfg["interpolation"], resample=False, ) ax.set_aspect("equal")
if cfg["show_axes"]: ax.set_xlabel(r"$\operatorname{Re}(z)$") ax.set_ylabel(r"$\operatorname{Im}(z)$") else: ax.set_axis_off() if cfg["show_title"]: ax.set_title(cfg["title"]) fig.tight_layout()
if cfg["figure_path"]: fig.savefig( cfg["figure_path"], dpi=cfg["save_dpi"], bbox_inches="tight", pad_inches=0.05, ) if cfg["raw_path"]: plt.imsave(cfg["raw_path"], image, origin="lower")
if cfg["show"]: plt.show() else: plt.close(fig) return image, roots, root_index, iteration_count
|