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

使用solve_ivp输出的x、y数组计算半径r时报TypeError如何解决

错误原因

你调用的math.sqrt()是Python标准库面向单个标量数值设计的计算函数,无法直接接收numpy数组作为入参。sol_3.y[1,:]**2 + sol_3.y[0,:]**2返回的是和时间步等长的一维numpy数组,传入math.sqrt()就会触发该类型错误。

修复方案

替换为支持逐元素运算的numpy平方根函数np.sqrt()即可,完整可运行参考代码如下:

import numpy as np
import math
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt

# 此处省略你提前定义的motion微分方程函数、initial初始值代码
timing = np.array([0,2*math.pi]) #t0 = 0 tf=2pi
sol_3 = solve_ivp(fun = motion, t_span=[-math.pi, 2*math.pi], y0 = initial, method='RK23')
x = sol_3.y[0, :]
y = sol_3.y[1, :]

# 替换math.sqrt为np.sqrt完成数组级运算
r = np.sqrt(y**2 + x**2)

# 绘制r(t)曲线示例
plt.plot(sol_3.t, r)
plt.xlabel('时间t')
plt.ylabel('半径r(t)')
plt.title('半径随时间变化曲线')
plt.grid(True)
plt.show()

内容的提问来源于stack exchange,提问作者Laura V.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:06:01