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

ddeint库PyPI首个示例无法运行报错求助(Python3.9)

解决ddeint示例代码中"ValueError: setting an array element with a sequence"错误

这个错误的核心原因是初始条件函数返回标量值,而ddeint内部处理延迟微分方程时,要求状态变量以数组形式存在,导致后续结果数组的形状无法统一。

修改方案及完整代码

只需调整初始条件的返回格式,并适配模型函数中的变量引用:

from pylab import cos, linspace, subplots
import numpy as np
from ddeint import ddeint

def model(Y, t):
    # 从数组中提取标量值计算
    y_t = Y(t)[0]
    return -Y(t - 3 * cos(y_t) ** 2)

def values_before_zero(t):
    # 返回一维数组而非标量
    return np.array([1])

tt = linspace(0, 30, 2000)
yy = ddeint(model, values_before_zero, tt)

fig, ax = subplots(1, figsize=(4, 4))
# 从二维结果数组中提取标量序列绘图
ax.plot(tt, yy[:, 0])
ax.figure.savefig("variable_delay.jpeg")

关键修改点说明

  • 初始条件函数values_before_zero返回np.array([1]),确保输出符合ddeint对状态变量的维度要求
  • 模型函数中先提取Y(t)的标量值y_t,避免对数组直接调用三角函数时的维度冲突
  • 绘图时取yy[:, 0],从ddeint返回的二维结果数组中提取出可直接绘图的标量序列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:45:53