北屋教程网

专注编程知识分享,从入门到精通的编程学习平台

用大语言模型使用 Python 构建一个 Lissajous 曲线

Lissajous 曲线是一个参数曲线,通常通过两个不同频率和相位的和谐振荡来描述。它是二维傅里叶变换的可视表示。

用 Trae 通过 DeepSeek V3-0324 自动生成代码,一次通过。

import numpy as np

import matplotlib . pyplot as plt

from matplotlib . animation import FuncAnimation

class LissajousCurve :

def __init__ ( self , ax , A , B , a , b , delta = 0 ):

"""

Create a Lissajous curve.

Parameters:

ax : axes object

A, B : amplitude for x and y oscillations

a, b : frequency for x and y oscillations

delta : phase difference

"""

self . ax = ax

self . A = A

self . B = B

self . a = a

self . b = b

self . delta = delta

self . t = np . linspace ( 0 , 2 * np . pi , 500 )

self . x = self . A * np . sin ( self . a * self . t + self . delta )

self . y = self . B * np . sin ( self . b * self . t )

# Initialize line and point with empty data

self . line , = ax .plot([], [], 'r-' ) # Red line

self . point , = ax .plot([], [], 'bo' ) # Blue point

def init ( self ):

""" Initialize the plot. Clear the line and point. """

self . line .set_data([], [])

self . point .set_data([], [])

return self . line , self . point ,

def update ( self , frame ):

"""

Update line and point based on the current frame.

"""

# 添加边界检查

if frame >= len ( self . x ):

frame = len ( self . x ) - 1

# 确保数据是序列类型

line_x = self . x [: frame + 1 ] if frame > 0 else []

line_y = self . y [: frame + 1 ] if frame > 0 else []

self . line .set_data( line_x , line_y )

self . point .set_data([ self . x [ frame ]], [ self . y [ frame ]]) # 确保传入的是序列

return self . line , self . point ,

# Create a figure and axis

fig , ax = plt . subplots ( figsize = ( 6 , 6 ))

ax . set_xlim ( - 2.5 , 2.5 )

ax . set_ylim ( - 2 , 2 )

ax . set_aspect ( 'equal' ) # Ensure the aspect ratio is equal

ax . set_title ( "Dynamic Lissajous Curve (A=2, B=1, a=3, b=4)" )

# Create the LissajousCurve object

lc = LissajousCurve ( ax , A = 2 , B = 1 , a = 3 , b = 4 , delta = np . pi / 2 )

# Call FuncAnimation to create an animation

ani = FuncAnimation ( fig , lc . update , frames = 500 , init_func = lc . init , blit = True , interval = 20 )

# 保存为 GIF 文件

ani . save ( 'd:/py_stu/test/lissajous.gif' , writer = 'pillow' , fps = 24 )

# Show the animation

plt . show ()

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言