用离散值近似拟合连续值,可以用于快速理解题意。
import numpy as np
from matplotlib import pyplot as plt
import math
n = 240
x = np.zeros(shape=(4,n))
y = np.zeros(shape=(4,n))
x[0,0] = 100
y[0,0] = 0
x[1,0] = 0
y[1,0] = 0
x[2,0] = 0
y[2,0] = 100
x[3,0] = 100
y[3,0] = 100
def compute_direct(i,j):
i2 = (i+1)%4
cos_theta = (x[i2,j]-x[i,j]) / math.sqrt((x[i2,j]-x[i,j]) ** 2 + (y[i2,j]-y[i,j]) ** 2)
sin_theta = (y[i2,j]-y[i,j]) / math.sqrt((x[i2,j]-x[i,j]) ** 2 + (y[i2,j]-y[i,j]) ** 2)
return cos_theta, sin_theta
def move(i,j,v,dt):
cos_theta, sin_theta = compute_direct(i,j)
x[i,j+1] = x[i,j] + v * dt * cos_theta
y[i,j+1] = y[i,j] + v * dt * sin_theta
dt = 0.05
v = 10
for _ in range(n-1):
for i in range(4):
move(i,_,v,dt)
plt.plot(x[0],y[0],‘red‘, label=‘A‘)
plt.plot(x[1],y[1],‘green‘, label=‘B‘)
plt.plot(x[2],y[2],‘blue‘, label=‘C‘)
plt.plot(x[3],y[3],‘black‘, label=‘D‘)
plt.legend()
plt.show()