python绘制分形图基础_Python 绘制分形图(曼德勃罗集、分形树叶、科赫曲线、分形龙、谢尔宾斯基三角等)附代码...
时间: 2023-07-10 20:03:46 浏览: 206
以下是Python绘制分形图的基础方法,包括曼德勃罗集、分形树叶、科赫曲线、分形龙、谢尔宾斯基三角等。
1. 曼德勃罗集
曼德勃罗集是一种非常著名的分形图形,可以用Python来绘制。代码如下:
```python
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot(c, max_iters=100):
z = c
n = 0
while abs(z) <= 2 and n < max_iters:
z = z*z + c
n += 1
if n == max_iters:
return 0
else:
return n
def mandelbrot_set(xmin, xmax, ymin, ymax, width, height, max_iters=100):
r1 = np.linspace(xmin, xmax, width)
r2 = np.linspace(ymin, ymax, height)
return np.array([[mandelbrot(complex(r, i), max_iters) for r in r1] for i in r2])
plt.imshow(mandelbrot_set(-2.0, 0.5, -1.25, 1.25, 1000, 1000, 100), cmap='hot')
plt.axis('off')
plt.show()
```
2. 分形树叶
分形树叶是一种美丽的分形图形,可以用Python来绘制。代码如下:
```python
import turtle
def draw_branch(branch_len, pensize):
if branch_len > 5:
turtle.forward(branch_len)
turtle.right(20)
turtle.pensize(pensize - 1)
draw_branch(branch_len - 15, pensize - 1)
turtle.left(40)
draw_branch(branch_len - 15, pensize - 1)
turtle.right(20)
turtle.backward(branch_len)
turtle.speed('fastest')
turtle.left(90)
turtle.penup()
turtle.backward(200)
turtle.pendown()
turtle.pensize(10)
turtle.color('brown')
draw_branch(100, 10)
turtle.done()
```
3. 科赫曲线
科赫曲线是一种经典的分形图形,可以用Python来绘制。代码如下:
```python
import turtle
def koch_curve(length, depth):
if depth == 0:
turtle.forward(length)
return
length = length / 3
koch_curve(length, depth - 1)
turtle.left(60)
koch_curve(length, depth - 1)
turtle.right(120)
koch_curve(length, depth - 1)
turtle.left(60)
koch_curve(length, depth - 1)
turtle.penup()
turtle.goto(-300, -100)
turtle.pendown()
turtle.color('blue')
turtle.pensize(2)
koch_curve(600, 4)
turtle.done()
```
4. 分形龙
分形龙是一种神奇的分形图形,可以用Python来绘制。代码如下:
```python
import turtle
def dragon_curve(length, depth, sign=1):
if depth == 0:
turtle.forward(length)
return
turtle.right(45 * sign)
dragon_curve(length / (2 ** 0.5), depth - 1, 1)
turtle.left(90 * sign)
dragon_curve(length / (2 ** 0.5), depth - 1, -1)
turtle.right(45 * sign)
turtle.penup()
turtle.goto(-200, -200)
turtle.pendown()
turtle.color('green')
turtle.pensize(2)
dragon_curve(400, 12)
turtle.done()
```
5. 谢尔宾斯基三角
谢尔宾斯基三角是一种经典的分形图形,可以用Python来绘制。代码如下:
```python
import turtle
def sierpinski_triangle(length, depth):
if depth == 0:
for i in range(3):
turtle.forward(length)
turtle.left(120)
return
sierpinski_triangle(length / 2, depth - 1)
turtle.forward(length / 2)
sierpinski_triangle(length / 2, depth - 1)
turtle.backward(length / 2)
turtle.left(60)
turtle.forward(length / 2)
turtle.right(60)
sierpinski_triangle(length / 2, depth - 1)
turtle.left(60)
turtle.backward(length / 2)
turtle.right(60)
turtle.penup()
turtle.goto(-200, -200)
turtle.pendown()
turtle.color('orange')
turtle.pensize(2)
sierpinski_triangle(400, 5)
turtle.done()
```
以上是Python绘制分形图的基础方法,希望对你有所帮助。
阅读全文