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

Sympy lambdify调用NumPy时触发ufunc不支持Mul类型报错

报错根因

报错loop of ufunc does not support argument 0 of type Mul which has no callable sin method是因为你传入numpy后端lambdify函数的参数中包含Sympy符号对象,numpy的三角函数通用函数无法识别Sympy的Mul(乘积)类型对象,无法执行运算。

具体触发点在参数定义部分:

theta_0, sigma_theta = 45*sp.pi/180, 1*sp.pi/180

sp.pi是Sympy定义的符号常量,不是原生浮点数,因此np.random.normal(theta_0, sigma_theta)生成的rand_theta是Sympy对象而非numpy浮点数,传入依赖numpy运算的函数时直接触发报错。

除此之外代码还有两处会导致运行异常的问题:

  • 未导入matplotlib.pyplot
  • t_end_func调用时参数顺序和定义不匹配:定义lambdify时入参顺序为[y_0, v, theta],但调用时写为t_end_func(rand_v, rand_theta, float(50)),即便类型正确计算结果也完全错误。

你之前遇到该问题偶尔自行消失,本质是某次运行时传入的参数刚好是纯数值类型,没有混入Sympy符号对象。

修复方案
  • 所有用于数值计算的常量全部转成原生浮点数或numpy数值,不要保留Sympy类型,角度转弧度直接用np.pi替代sp.pi即可
  • 修正t_end_func的调用参数顺序,和定义保持一致
  • 补上matplotlib的导入
  • 核心原则:用modules="numpy"/modules=np生成的lambdify函数,所有传入参数必须是纯Python数值或者numpy数组/数值,不能传入任何Sympy的符号、表达式对象,否则就会触发同类报错。
修复后完整可运行代码
import sympy as sp
import numpy as np
import scipy.constants as const
import matplotlib.pyplot as plt

# 符号定义
g, t, theta, t_max, v, x_0, y_0, y_f = sp.symbols("g t theta t_max v x_0 y_0 y_f")
# 轨迹方程
x = x_0 + v*sp.cos(theta)*t
y = y_0 + v*sp.sin(theta)*t + sp.Rational(1,2)*g*t**2

# 求解落地时间,取正根
t_end = sp.solve(sp.Eq(y,0),t)[1]
# lambdify入参顺序固定为[y_0, v, theta]
t_end_func = sp.lambdify([y_0,v, theta], t_end.subs(g,const.g), modules="numpy")
x_func = sp.lambdify([x_0, v, theta, t], x, modules=np)
y_func = sp.lambdify([y_0, v, theta, t], y.subs(g, -const.g), modules=np)

# 数值参数全部转成纯浮点数,不保留Sympy类型
v_0 , sigma_v = 200, 1 # m/s
theta_0, sigma_theta = 45*np.pi/180, 1*np.pi/180 # 角度转弧度


fig1, ax1 = plt.subplots()
ax1.set_title(f"Bahnkurven mit normalverteilten $\\Theta$ und $v$")
ax1.set_xlabel("$x$")
ax1.set_ylabel("$y$")

anz_kurven = int(1e2)
for i in range(anz_kurven):
    rand_v = np.random.normal(v_0, sigma_v)
    rand_theta = np.random.normal(theta_0, sigma_theta)
    # 按定义顺序传参:y0=50, v=rand_v, theta=rand_theta
    t_total = t_end_func(50, rand_v, rand_theta)
    zeitpunkte = np.linspace(0, t_total, 100)
    ax1.plot(x_func(100, rand_v, rand_theta, zeitpunkte), y_func(50, rand_v, rand_theta, zeitpunkte), color="#0000FF50")

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 02:01:08