Python 中微积分函数的图形速度和距离

Graph velocity and distance from calculus functions in Python

有没有更简单的代码方式,我可以更轻松地在微积分问题中实现绘制以下分段函数的图形?在我的方法中,我使用了 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');

您可以使用 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可读性不是很好,但是绝对省了一些代码行

您可以根据您的条件使用np.where分配您的v(t)f(t)。您不需要任何 for 循环。矢量化方法使您的代码更加简洁。在np.where中,首先检查条件,然后将条件后的第一个值赋给条件成立的索引True,第二个值赋给条件成立的索引[=16] =].

下面是一个例子:

import numpy as np
import matplotlib.pyplot as plt

# Initialise time
t_1 = np.arange(1,20,1)/100
t_2 = np.arange(21,40,1)/100

# Compute v(t)
v_1 = np.where(t_1<0.2, 20, 0)
v_2 = np.where(t_2<0.2, 20, 0)

# Compute f(t)
f_1 = np.where(t_1<=0.2, 20*t_1, 4)
f_2 = np.where(t_2<=0.2, 20*t_2, 4)

# Plotting as you are doing