写代码画曲线
写代码,利用公式(x² + y² - 1)³ - x²y³ = 0画连续、封闭心形曲线。 要绘制连续封闭的心形曲线,可以使用数学公式 \((x^2 + y^2 - 1)^3 - x^2 y^3 = 0\) 结合数值计算库和绘图库实现。以下是完整代码:import numpy as np
import matplotlib.pyplot as plt
# 创建网格数据
x = np.linspace(-2, 2, 10000)
y = np.linspace(-2, 2, 10000)
X, Y = np.meshgrid(x, y)
# 计算方程
F = (X**2 + Y**2 - 1)**3 - X**2 * Y**3
# 绘制等高线(F=0的轮廓)
plt.contour(X, Y, F, levels=, colors='red')
# 设置坐标轴比例相等
plt.axis('equal')
plt.title('Heart Curve')
plt.show()
### 代码说明:
1. **网格创建**:使用 np.linspace 生成-2到2范围内的均匀点
2. **方程计算**:直接套用心形公式计算每个网格点的值
3. **绘图关键**:plt.contour(levels=) 精确绘制方程=0的等高线
4. **图形优化**:plt.axis('equal') 确保坐标轴比例一致,保持心形不变形
运行效果:
- 显示一个完美的红色封闭心形曲线
- 曲线连续且无断裂
- 图形范围在坐标系[-2,2]区间内
> 提示:可通过调整 colors 参数修改曲线颜色,例如改为 colors='pink' 获得粉色心形。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 小甲鱼的二师兄 发表于 2025-6-28 14:09
用上面 AI 给的代码 有心人
{:10_257:} 有趣,画成动态的超级有趣 数学届的恋爱曲线 {:5_106:} {:5_105:} {:10_275:} Traceback (most recent call last):
File "C:/Users/***/Desktop/python专用/1.py", line 1, in <module>
import numpy as np
ModuleNotFoundError: No module named 'numpy' import pygame
import sys
import math
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("爱心曲线")
BACKGROUND = (10, 10, 30)# 深蓝色背景
HEART_COLOR = (255, 0, 85)# 鲜艳的粉红色
TEXT_COLOR = (200, 200, 255)# 淡蓝色文字
font = pygame.font.SysFont('kaiti', 36)
font1 = pygame.font.SysFont(None, 36)
# 坐标转换函数:将数学坐标转换为屏幕坐标
def to_screen(x, y):
scale = 180# 缩放比例
# 将坐标原点移到屏幕中心,并翻转y轴
return WIDTH // 2 + int(x * scale), HEIGHT // 2 - int(y * scale)
# 计算爱心方程
def heart_equation(x, y):
# 计算方程左边的值
return (x ** 2 + y ** 2 - 1) ** 3 - (x ** 2) * (y ** 3)
# 主函数
def main():
clock = pygame.time.Clock()
points = []
animation_phase = 0# 动画相位
# 预计算点集
for x in :
for y in :
# 检查点是否满足方程(允许一定误差)
if abs(heart_equation(x, y)) < 0.005:
points.append((x, y))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
# 填充背景
screen.fill(BACKGROUND)
# 绘制坐标轴
pygame.draw.line(screen, (50, 50, 80), (0, HEIGHT // 2), (WIDTH, HEIGHT // 2), 1)
pygame.draw.line(screen, (50, 50, 80), (WIDTH // 2, 0), (WIDTH // 2, HEIGHT), 1)
# 更新动画参数
animation_phase = (animation_phase + 0.02) % (2 * math.pi)
pulse_size = 1.0 + 0.1 * math.sin(animation_phase)
# 绘制所有点(带缩放动画)
for (x, y) in points:
sx, sy = to_screen(x * pulse_size, y * pulse_size)
pygame.draw.circle(screen, HEART_COLOR, (sx, sy), 15)
# 绘制标题和方程
title = font.render("爱心曲线", True, TEXT_COLOR)
equation = font1.render("(x² + y² - 1)³ - x²y³ = 0", True, TEXT_COLOR)
screen.blit(title, (WIDTH // 2 - title.get_width() // 2, 20))
screen.blit(equation, (WIDTH // 2 - equation.get_width() // 2, HEIGHT - 50))
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
if __name__ == "__main__":
main() {:10_254:}
页:
[1]