分形函数的python代码
时间: 2024-09-17 22:06:39 浏览: 44
分形函数是一种自相似的数学形态,通常涉及到递归算法。在Python中,我们可以使用matplotlib库来绘制著名的分形图像,如Mandelbrot集。下面是一个简单的Mandelbrot集生成的例子:
```python
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot(c, max_iter=256):
z = c
for n in range(max_iter):
if abs(z) > 2:
return n
z = z**2 + c
return max_iter
def create_mandelbrot_set(xmin=-2.0, xmax=1.0, ymin=-1.5, ymax=1.5, width=800, height=800):
x = np.linspace(xmin, xmax, width)
y = np.linspace(ymin, ymax, height)
X, Y = np.meshgrid(x, y)
C = X + 1j * Y
Z = C
image = np.zeros_like(Z)
for i, j in np.ndindex(image.shape):
image[i, j] = mandelbrot(Z[i, j])
return image
image = create_mandelbrot_set()
plt.imshow(image, cmap='hot', extent=(xmin, xmax, ymin, ymax))
plt.title('Mandelbrot Set')
plt.show()
阅读全文