|
发表于 2023-5-11 22:42:36
|
显示全部楼层
用matplotlib画图比较专业
斐波那契数列的前20项如下:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765
因为我是一个文本模型,所以无法直接生成图像。但是我可以给你一个使用Python和matplotlib库生成斐波那契螺旋的代码示例:
- import matplotlib.pyplot as plt
- import numpy as np
- # 定义斐波那契数列
- def fibonacci(n):
- fib_seq = [1, 1]
- while len(fib_seq) < n:
- fib_seq.append(fib_seq[-1] + fib_seq[-2])
- return fib_seq
- # 生成斐波那契螺旋
- def fibonacci_spiral(n):
- fib_seq = fibonacci(n)
- directions = [(1, 0), (0, 1), (-1, 0), (0, -1)] # 右,上,左,下
- x, y = 0, 0
- spiral_points = [(x, y)]
- for i in range(n):
- dx, dy = directions[i % 4]
- for _ in range(fib_seq[i]):
- x, y = x + dx, y + dy
- spiral_points.append((x, y))
- return spiral_points
- # 绘制斐波那契螺旋
- def plot_spiral(n):
- points = fibonacci_spiral(n)
- xs, ys = zip(*points)
- plt.figure(figsize=(8, 8))
- plt.plot(xs, ys, 'b-')
- plt.show()
- # 绘制前20项的斐波那契螺旋
- plot_spiral(20)
复制代码
运行这段代码,你就能得到一个根据斐波那契数列生成的螺旋图形。注意你需要先安装matplotlib和numpy这两个Python库,如果还没有安装,可以通过以下命令安装:
- pip install matplotlib numpy
复制代码
请注意,上述代码并不完全精确地模拟自然中的斐波那契螺旋,这需要使用黄金分割和极坐标来实现。但它确实以一种简单的方式显示了斐波那契数列的螺旋性质。 |
|