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

PyPlot绘图报错:数组无法转换为Python标量,求解决方案

解决TypeError: only size-1 arrays can be converted to Python scalars报错问题

报错原因

  • math.sqrt()仅支持单个Python标量值运算,你定义的T是numpy.arange()生成的数组,将数组传入math.sqrt()时就会触发该错误。这也是单个整数T能正常运行的原因——单个数值属于标量,符合math.sqrt()的输入要求。
  • 原代码的括号嵌套逻辑错误,导致公式计算逻辑偏离预期。

修正后的代码

import numpy as np
import matplotlib.pyplot as plt

m=20  # kg
Ft=300  # N
Fg=-100  # N
F=Ft+Fg
Ar=F/m
Vro=5  # m/s
T=np.arange(0.2,2,.2)  # s
R=3  # m
L=8  # m

# 替换为numpy的sqrt函数并修正括号逻辑
Vd = np.sqrt( ((L + Vro*T + 0.5*Ar*T**2) + L)**2 + R**2 ) / T

plt.plot(T, Vd,'r')
plt.show()

关键修正点

  • 用np.sqrt()替代math.sqrt():numpy的sqrt函数支持数组元素级运算,可直接处理T这类numpy数组。
  • 调整括号结构:确保根号包裹的是完整的目标表达式,符合物理公式的计算逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:20:40