|
| 1 | +import matplotlib.pyplot as plt |
| 2 | +import numpy as np |
| 3 | +import warnings |
| 4 | + |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +def compute_mandelbrot(max_iter: int, threshold: float, width: int, height: int) -> np.ndarray: |
| 8 | + """ |
| 9 | + Computes the Mandelbrot set over a specified grid. |
| 10 | +
|
| 11 | + Parameters: |
| 12 | + - max_iter: maximum number of iterations per point |
| 13 | + - threshold: escape threshold |
| 14 | + - width: number of points along the x-axis |
| 15 | + - height: number of points along the y-axis |
| 16 | + """ |
| 17 | + x = np.linspace(-2, 1, width) |
| 18 | + y = np.linspace(-1.5, 1.5, height) |
| 19 | + c = x[:, None] + 1j * y[None, :] |
| 20 | + |
| 21 | + z = c.copy() |
| 22 | + |
| 23 | + # Suppress any overflow. |
| 24 | + with warnings.catch_warnings(): |
| 25 | + warnings.simplefilter("ignore") |
| 26 | + for _ in range(max_iter): |
| 27 | + z = z**2 + c |
| 28 | + mandelbrot_set = (np.abs(z) < threshold) |
| 29 | + |
| 30 | + return mandelbrot_set |
| 31 | + |
| 32 | +if __name__ == '__main__': |
| 33 | + MAX_ITER = 50 |
| 34 | + THRESHOLD = 50.0 |
| 35 | + WIDTH = 600 |
| 36 | + HEIGHT = 400 |
| 37 | + |
| 38 | + mandelbrot_set = compute_mandelbrot(MAX_ITER, THRESHOLD, WIDTH, HEIGHT) |
| 39 | + |
| 40 | + plt.imshow(mandelbrot_set.T, extent=[-2, 1, -1.5, 1.5]) |
| 41 | + |
| 42 | + # Save the file and print out where it was located. |
| 43 | + file_path = Path('example.png') |
| 44 | + plt.savefig(file_path) |
| 45 | + print("File created at:\n\t{}".format(file_path.resolve())) |
0 commit comments