Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Barnsley Fern ใน Python: สร้างรูปเฟิร์นด้วย Iterated Function System

ในบทช่วยสอนนี้ เราจะเรียนรู้เกี่ยวกับ Barnsley Fern ซึ่งเป็นรูปแบบ frattal ที่สร้างโดย Michael Barnsley รูปทรงคล้ายใบเฟิร์น สร้างขึ้นโดยการวนซ้ำ (iterate) สมการทางคณิตศาสตร์ 4 สมการ ที่เรียกว่า Iterated Function System (IFS)

สูตรการแปลง

f(x,y) = [[a, b], [c, d]] × [x, y] + [e, f]

ค่าพารามิเตอร์ของแต่ละการแปลง:

Barnsley Fern ใน Python: สร้างรูปเฟิร์นด้วย Iterated Function System

แหล่งที่มา: Wikipedia

สมการ 4 สมการของ Barnsley Fern:

Barnsley Fern ใน Python: สร้างรูปเฟิร์นด้วย Iterated Function System

แหล่งที่มา: Wikipedia

โค้ด Python สำหรับสร้าง Barnsley Fern

import matplotlib.pyplot as plot
import random

x = [0]
y = [0]
current = 0

for i in range(1, 100000):
    z = random.randint(1, 100)
    
    if z == 1:
        x.append(0)
        y.append(0.16 * y[current])
    elif 2 <= z <= 86:
        x.append(0.85 * x[current] + 0.04 * y[current])
        y.append(-0.04 * x[current] + 0.85 * y[current] + 1.6)
    elif 87 <= z <= 93:
        x.append(0.2 * x[current] - 0.26 * y[current])
        y.append(0.23 * x[current] + 0.22 * y[current] + 1.6)
    elif 94 <= z <= 100:
        x.append(-0.15 * x[current] + 0.28 * y[current])
        y.append(0.26 * x[current] + 0.24 * y[current] + 0.44)
    
    current += 1

plot.scatter(x, y, s=0.2, edgecolor='green')
plot.show()

ผลลัพธ์

Barnsley Fern ใน Python: สร้างรูปเฟิร์นด้วย Iterated Function System

สรุป

Barnsley Fern เป็นตัวอย่างคลาสสิกของ Fractal ที่สร้างจาก IFS (Iterated Function System) โดยใช้ความน่าจะเป็นในการเลือกการแปลงแต่ละครั้ง อ้างอิง: Wikipedia หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็น