python 写的爱心程序,超级漂亮
作者:野牛程序员:2023-03-11 13:22:30python阅读 2929
用python写的爱心程序,超级漂亮,代码如下:
import matplotlib.pyplot as plt import numpy as np # 生成大爱心的坐标数据 t = np.linspace(0, 2 * np.pi, 1000) x = 16 * np.sin(t)**3 y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t) # 生成小爱心的坐标数据 t2 = np.linspace(0, 2 * np.pi, 500) x2 = 4 * np.sin(t2)**3 y2 = 3 * np.cos(t2) - 1.25 * np.cos(2 * t2) - 0.5 * np.cos(3 * t2) - 0.25 * np.cos(4 * t2) # 设置画布大小和背景颜色 fig, ax = plt.subplots(figsize=(8, 8)) ax.set_facecolor('black') # 绘制小爱心 ax.scatter(x2, y2, s=2, c='red', alpha=0.8) # 绘制大爱心 ax.plot(x, y, color='red', linewidth=3) ax.fill_between(x, y, color='red', alpha=0.3) # 在大爱心周围随机生成小爱心的坐标,并限制在大爱心内部 N = 1000 r = 8 # 小爱心的半径 theta = 2 * np.pi * np.random.rand(N) s = r * np.sqrt(np.random.rand(N)) # 限制在大爱心内部 x3 = s * np.sin(theta) + 16 y3 = s * np.cos(theta) + 13 x3, y3 = x3[np.where((x3-16)**2 + (y3-13)**2 <= 169)], y3[np.where((x3-16)**2 + (y3-13)**2 <= 169)] # 绘制周围小爱心 ax.scatter(x3, y3, s=1, c='red', alpha=0.4) # 隐藏坐标轴 ax.axis('off') # 显示图形 plt.show()
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892