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

2024-04-18 05:45:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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');

Tags: inforreturniftimeplotdefrange
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的可读性不强,但它确实节省了一些代码行

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

下面是一个例子:

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

enter image description here

相关问题 更多 >