You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将多组随机变量列表循环传入d_oscil函数并输出对应计算值

实现方法

你生成的三个随机参数列表长度均为5,元素一一对应,直接按组遍历传入d_oscil函数即可,以下是两种常用实现方式:

方法1:按索引遍历

# 固定w参数
w = np.pi * 2
# 存储计算结果
y_result = []

for i in range(len(l_random_list)):
    # 取出对应位置的参数
    l = l_random_list[i]
    f = f_random_list[i]
    t = t_random_list[i]
    # 调用函数计算y值
    y = d_oscil(l, w, f, t)
    y_result.append(y)
    # 打印参数和对应结果
    print(f"第{i+1}组:l={l:.3f},f={f:.3f},t={t:.3f},计算值y={y:.3f}")

方法2:zip打包遍历(更简洁)

不用手动处理索引,直接打包三个列表同步遍历:

w = np.pi * 2
y_result = []

for idx, (l, f, t) in enumerate(zip(l_random_list, f_random_list, t_random_list)):
    y = d_oscil(l, w, f, t)
    y_result.append(y)
    print(f"第{idx+1}组:l={l:.3f},f={f:.3f},t={t:.3f},计算值y={y:.3f}")

扩展:多组参数绘制完整振荡曲线

如果你需要为每一组随机的l、f参数绘制0~5秒的完整振荡曲线,可以用以下代码:

plt.figure(num=1, dpi=150)
# 绘制上下包络线
plt.plot(t_list, np.exp(-t_list), color='red', linestyle='--', label='上包络')
plt.plot(t_list, -np.exp(-t_list), color='red', linestyle='--', label='下包络')

# 遍历每组参数生成曲线
for l, f in zip(l_random_list, f_random_list):
    y_curve = d_oscil(l, np.pi*2, f, t_list)
    plt.plot(t_list, y_curve, alpha=0.7, label=f'l={l:.2f}, f={f:.2f}')

# 样式设置和原有逻辑保持一致
plt.axhline(0, color='black', linestyle='-')
plt.axvline(0, color='black', linestyle='-')
plt.ylim(-1.2, 1.2)
plt.xlim(0, 5)
plt.title('多组参数阻尼振荡曲线')
plt.xlabel('时间')
plt.ylabel('位移')
plt.legend(fontsize=6)
plt.show()

内容的提问来源于stack exchange,提问作者Dominic Matthews

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 10:06:03