酷代码 AI
菜单
服务商

百行Python代码:解锁参数、ASCII、笛卡尔及3D多种爱心生成法与避坑指南

```python import numpy as np import matplotlib.pyplot as plt import math def generate_heart_points(num_points=1000): """ 生成爱心形状的坐标点 """ t = np.linspace(0, 2 * np.pi, num_points) # 爱心参数方程 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) return x, y def create_heart_plot(): """ 创建爱心图形 """ # 设置图形大小 plt.figure(figsize=(8, 8)) # 生成爱心坐标 x, y = generate_heart_points() # 绘制爱心轮廓 plt.plot(x, y, color='red', linewidth=3, label='Heart Outline') # 填充爱心 plt.fill(x, y, 'pink', alpha=0.7, label='Heart Fill') # 设置图形属性 plt.axis('equal') plt.axis('off') plt.title('Beautiful Heart Shape', fontsize=16, fontweight='bold') plt.legend() # 添加网格 plt.grid(True, alpha=0.3) return plt def print_heart_ascii(): """ 打印ASCII艺术爱心 """ heart_ascii = [ " ", " ", " ", "*", " * ", " * ", " * ", " * ", " * ", " * ", " * ", " * " ] print("ASCII Heart:") for line in heart_ascii: print(line) def calculate_heart_area(): """ 计算爱心近似面积 """ x, y = generate_heart_points(5000) # 使用梯形法则计算面积 area = 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) return area def create_animated_heart(): """ 创建动态爱心效果(简化版) """ fig, ax = plt.subplots(figsize=(8, 8)) for scale in np.linspace(0.5, 1.5, 10): t = np.linspace(0, 2 * np.pi, 200) x = scale * 16 * np.sin(t) 3 y = scale * (13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t)) ax.clear() ax.plot(x, y, 'red', linewidth=2) ax.fill(x, y, 'pink', alpha=0.6) ax.set_xlim(-20, 20) ax.set_ylim(-20, 20) ax.axis('equal') ax.axis('off') ax.set_title(f'Heart Scale: {scale:.1f}') plt.pause(0.5) plt.show() def heart_function(x): """ 爱心函数(笛卡尔坐标系) """ return np.sqrt(1 - (np.abs(x) - 1) 2), -3 * np.sqrt(1 - np.sqrt(np.abs(x) / 2)) def create_cartesian_heart(): """ 使用笛卡尔坐标系创建爱心 """ x = np.linspace(-2, 2, 1000) y_upper, y_lower = heart_function(x) plt.figure(figsize=(8, 8)) plt.plot(x, y_upper, 'red', linewidth=2) plt.plot(x, y_lower, 'red', linewidth=2) plt.fill_between(x, y_upper, y_lower, color='pink', alpha=0.7) plt.axis('equal') plt.axis('off') plt.title('Cartesian Heart') plt.show() def generate_3d_heart(): """ 生成3D爱心(简化版) """ fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(111, projection='3d') # 生成3D爱心参数 u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) # 3D爱心参数方程 x = 16 * np.sin(u) 3 y = 13 * np.cos(u) - 5 * np.cos(2*u) - 2 * np.cos(3*u) - np.cos(4*u) z = np.ones_like(x) * 2 # 简单的高度 ax.plot(x, y, z, color='red', linewidth=3) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.set_title('3D Heart') plt.show() def main(): """ 主函数 - 展示所有爱心效果 """ print("=" * 50) print(" Python Heart Generator") print("=" * 50) # 打印ASCII爱心 print_heart_ascii() print() # 计算并显示爱心面积 area = calculate_heart_area() print(f"Approximate heart area: {area:.2f} square units") print() # 创建标准爱心图形 print("Creating standard heart plot...") plt_std = create_heart_plot() plt_std.show() # 创建笛卡尔坐标系爱心 print("Creating Cartesian heart...") create_cartesian_heart() # 显示爱心函数信息 print("Heart function information:") print("Parametric equations:") print("x = 16 * sin(t)^3") print("y = 13 * cos(t) - 5 * cos(2t) - 2 * cos(3t) - cos(4t)") print() # 显示一些数学属性 x_points, y_points = generate_heart_points(100) print(f"Number of points generated: {len(x_points)}") print(f"X range: [{min(x_points):.2f}, {max(x_points):.2f}]") print(f"Y range: [{min(y_points):.2f}, {max(y_points):.2f}]") # 询问用户是否要查看动态效果 user_input = input("\nWould you like to see animated heart? (y/n): ") if user_input.lower() == 'y': print("Creating animated heart...") create_animated_heart() print("\nThank you for using the Heart Generator!") # 添加一些工具函数 def heart_stats(): """ 计算爱心的统计信息 """ x, y = generate_heart_points() stats = { 'width': max(x) - min(x), 'height': max(y) - min(y), 'center_x': (max(x) + min(x)) / 2, 'center_y': (max(y) + min(y)) / 2, 'area': calculate_heart_area() } return stats def save_heart_image(filename='heart_plot.png'): """ 保存爱心图像到文件 """ plt = create_heart_plot() plt.savefig(filename, dpi=300, bbox_inches='tight', facecolor='white') print(f"Heart image saved as {filename}") # 运行主程序 if __name__ == "__main__": main() # 显示统计信息 stats = heart_stats() print("\nHeart Statistics:") for key, value in stats.items(): print(f"{key}: {value:.2f}") # 保存图像 save_heart_image() ``` 这段代码提供了多种爱心生成方式,包括参数方程爱心、ASCII艺术爱心、笛卡尔坐标系爱心和3D爱心效果。 我在以往的开发过程中,碰到过以下几点需要格外小心处理的地方: 1. 参数方程中三角函数计算要确保使用弧度制而非角度制 2. 图形填充时注意坐标点顺序,避免填充异常 3. 动态图形创建时要及时清理画布防止内存泄漏 ######[AI写代码神器 | 1926点数解答 | 2025-10-21 18:51:32]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]