用Python绘制速度和距微积分函数的距离

时间:2018-12-26 16:33:59

标签: python calculus

enter image description here

在微积分问题中,是否可以采用更多的代码实现方式来实现以下分段函数的图形化?在我的方法中,我使用了matplotlib并将图组合成两个主要图以显示不连续性。

import matplotlib.pyplot as plt

def v(time_range):
    velocity_val = []
    for i in time_range:
        if i < .2:
            velocity_val.append(20)
        elif i > .2:
            velocity_val.append(0)
    return velocity_val

def f(time_range):
    distance_val = []
    for i in time_range:
        if i <= .2:
            distance_val.append(20*i)
        if i >= .2:
            distance_val.append(4)
    return distance_val

def time_vals(time_range):
    decimal = 100
    time_val = []
    for i in time_range:
        num = i / decimal
        time_val.append(num)
    return time_val

#convert time into decimal
time_range_1 = range(1,20,1)
time_range_2 = range(21,40,1)
t_1 = time_vals(time_range_1)
t_2 = time_vals(time_range_2)

#get x, y for plot
v_1 = v(t_1)
v_2 = v(t_2)
f_1 = f(t_1)
f_2 = f(t_2)

#plot values into two graphs.
plt.subplot(2, 1, 1)
plt.plot(t_1, v_1)
plt.plot(t_2, v_2)
plt.title(' Problem 9')
plt.ylabel('Velocity')

plt.subplot(2, 1, 2)
plt.plot(t_1, f_1)
plt.plot(t_2, f_2)
plt.xlabel('time (t)')
plt.ylabel('Velocity');

2 个答案:

答案 0 :(得分:2)

您可以使用numpy对代码进行矢量化

也许像这样:

# Define time steps
t = np.linspace(0, 1, 100)
# Build v
v = np.empty_like(t)
v[.2 < t] = 20
v[.2 >= t] = 0
# Build f
f = np.empty_like(t)
f[t < 0.2] = 20 * t[t < 0.2]
f[t >= 0.2] = 4
# Plot
plt.plot(t, v)
plt.plot(t, d)

构建vf的另一种方法是使用np.piecewise

v = np.piecewise(t, [.2 < t, .2 >= t], [20, 0])
f = np.piecewise(t, [t <= .2, t > .2], [lambda x: 20 * x, 4])

我认为np.piecewise不太可读,但是肯定可以节省一些代码行

答案 1 :(得分:1)

您可以根据情况使用np.where来分配v(t)f(t)。您不需要任何for循环。向量化方法使您的代码更加简洁明了。在np.where中,首先检查条件,然后将条件后的第一个值分配给条件保持True的索引,将第二个值分配给条件保持{{1 }}。

下面是一个示例:

False

enter image description here