36 lines
977 B
Python
36 lines
977 B
Python
import numpy as np
|
|
import matplotlib.pyplot as plt
|
|
|
|
def fibonacci_spiral(n):
|
|
"""繪製費波那契螺旋"""
|
|
golden_ratio = (1 + np.sqrt(5)) / 2
|
|
theta = np.linspace(0, n * np.pi / 2, 1000)
|
|
r = golden_ratio ** (theta / (np.pi / 2))
|
|
|
|
x = r * np.cos(theta)
|
|
y = r * np.sin(theta)
|
|
|
|
plt.figure(figsize=(8, 8))
|
|
plt.plot(x, y, color='gold', linewidth=2)
|
|
|
|
# 增加方格來顯示費波那契數列
|
|
a, b = 1, 1
|
|
x, y = 0, 0
|
|
angle = 0
|
|
for _ in range(n):
|
|
plt.gca().add_patch(plt.Rectangle((x, y), a, a, fill=False, edgecolor='blue', linewidth=1.5))
|
|
x_new = x + a * np.cos(angle)
|
|
y_new = y + a * np.sin(angle)
|
|
a, b = b, a + b
|
|
angle -= np.pi / 2
|
|
x, y = x_new, y_new
|
|
|
|
plt.xlim([-b, b])
|
|
plt.ylim([-b, b])
|
|
plt.axis('equal')
|
|
plt.axis('off')
|
|
plt.title("Fibonacci Spiral", fontsize=14)
|
|
plt.show()
|
|
|
|
# 繪製前10個費波那契數的螺旋
|
|
fibonacci_spiral(10) |