Wil*_*l C 1 python scipy numerical-methods numerical-integration
我目前有一个python脚本,该脚本读取一个3列的文本文件,其中包含助行器的x和y坐标以及行人走路的时间。
我已读取此数据并将其分配给numpy数组,如以下代码所示:
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt("info.txt", delimiter = ',')
x = data[:,0]
y = data[:,1]
t = data[:,2]
Run Code Online (Sandbox Code Playgroud)
文件采用以下格式(x,y,t):
5907364.2371 -447070.881709 2193094
5907338.306978 -447058.019176 2193116
5907317.260891 -447042.192668 2193130
Run Code Online (Sandbox Code Playgroud)
现在,我想找到步行者随时间变化的距离。我可以想到的一种方法是在循环中将x坐标的差异和y坐标的所有差异相加。但是,这似乎是一个长篇大论的方法,我认为可以用一种数值积分方法来解决。有人对我能做什么有任何想法吗?
要“沿途”计算距离,您必须首先获取每个步骤的距离。
这可以通过indexing在组件方面获得dx = x[1:]-x[:-1]。这样,每步的距离就是“ dx ** 2 + dy ** 2的平方根”。请注意,此数组的长度要少一,因为步数相对应的间隔要少一个。这可以通过将距离“ 0”分配给首次数据来完成。这是下面“连接”行的角色。
这里没有数值积分,但是有一个累加和。要进行数值积分,您将需要运动方程(例如)。
额外的更改:我np.loadtxt与unpack=True参数一起使用以节省几行。
import numpy as np
import matplotlib.pyplot as plt
x, y, t = np.loadtxt("info.txt", unpack=True)
dx = x[1:]-x[:-1]
dy = y[1:]-y[:-1]
step_size = np.sqrt(dx**2+dy**2)
cumulative_distance = np.concatenate(([0], np.cumsum(step_size)))
plt.plot(t, cumulative_distance)
plt.show()
Run Code Online (Sandbox Code Playgroud)