# 线性跟驰模型车头间距

```import matplotlib.pyplot as plt
import numpy as np

class Linear():
"""
a(n+1)=C*(v(n)-v(n+1))，a为T时间后的加速度
C=λ*T
λ=1/(e*T)
假设初始8辆车正常运行

后车跟随前车，分别8->7->6->5->4->3->2->1
"""

def __init__(self, C):
"""初始化参数，舍弃0车，假定v0为平衡状态速度，其中1位前车，8为尾车"""
self.L = 5
self.C = C
self.T = 1
self.a = [0] * 9
self.v = [20] * 9
self.x = [0] * 9
self.s = [self.v[0] * self.T + self.L] * 8
self.x[8] = 0
for i in range(8, 1, -1):
self.x[i - 1] = self.x[i] + self.L + self.v[0] * self.T
self.acce = []
self.acce.append(self.a[1:])
self.speed = []
self.speed.append(self.v[1:])
self.disp = []
self.disp.append(self.x[1:])
self.gap = []
self.gap.append(self.s[1:])

def alter_acce(self):
if self.a[1] == 0:
self.a[1] = 6
# self.a[1] = -self.a[1]

def get_acce(self):
for i in range(2, 9):
self.a[i] = self.C * (self.v[i - 1] - self.v[i])
self.a[i] = round(self.a[i], 2)

def get_speed(self):
for i in range(1, 9):
self.v[i] = self.v[i] + self.a[i] * self.T
self.v[i] = round(self.v[i], 2)

def get_disp(self):
for i in range(1, 9):
self.x[i] = self.v[i] * self.T + 0.5 * self.a[i] * self.T * self.T + self.x[i]
self.x[i] = round(self.x[i], 2)

def get_gap(self):
for i in range(1, 8):
self.s[i] = self.x[i] - self.x[i + 1]
self.s[i] = round(self.s[i], 2)

def run(self):
for i in range(0, 100):
if i == 0:
self.alter_acce()
if i != 0:
self.a[1] = 0
self.get_acce()
self.acce.append(self.a[1:])
self.get_disp()
self.disp.append(self.x[1:])
self.get_speed()
self.speed.append(self.v[1:])
self.get_gap()
self.gap.append(self.s[1:])
if self.judge_end() <= 7 and self.judge_end() >= 1:
print("第{}个单位时间的时候第{}辆车和第{}辆车发生了碰撞".format(i + 1, self.judge_end(), self.judge_end() + 1))
# break
# self.draw_acce()
# self.draw_speed()
# self.draw_disp()
self.draw_gap()

def output(self):
"""
It is for test!
:return:
"""
pass

def judge_end(self):
for i in range(1, 8):
if self.x[i] - self.x[i + 1] <= self.L:
return i
return 0

def draw_acce(self):
new_acce = np.transpose(self.acce)
plt.title("accelerated speed-time")
for i in new_acce:
plt.plot(i)
plt.ylabel("accelerated velocity m/s^2")
plt.xlabel("time /T")
plt.show()

def draw_speed(self):
new_speed = np.transpose(self.speed)
plt.title("speed-time")
for item in new_speed:
plt.plot(item)
plt.ylabel("velocity m/s")
plt.xlabel("time /T")
plt.show()

def draw_disp(self):
new_disp = np.transpose(self.disp)
plt.title("displacement-time C={}".format(self.C))
for item in new_disp:
plt.plot(item)
plt.ylabel("displacement m")
plt.xlabel("time /T")
plt.show()

def draw_gap(self):
plt.title("gap-time C={}".format(self.C))
plt.axis([0,100,5,80])
new_gap = np.transpose(self.gap)
for item in new_gap:
plt.plot(item)
plt.ylabel("gap m")
plt.xlabel("time /T")
plt.show()

# C = input("请输入C的值：")
for i in range(1,30,3):
linear = Linear(i/10)
linear.run()
print("此时C的值是{}，T的值是{}s".format(linear.C, linear.T))```

47 篇文章28 人订阅

0 条评论

48860

25330

40660

34050

2.8K30

9820

370100

38850

15310

14450