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

Python绘图报错TypeError: only length-1 arrays can be converted to Python scalars

问题解决:TypeError 修复方案
  • 错误根源:math.exp() 仅支持单个数值输入,而代码中 (-h+(b/L)*t) 是一个numpy数组,传入math.exp()会触发类型错误。
  • 修复步骤:
    1. 替换 math.exp 为 np.exp,numpy的exp函数可直接处理数组,实现元素级运算。
    2. 移除表达式外层的[...]括号,numpy数组支持标量与数组直接运算,无需额外列表包裹。

修复后的完整代码:

import math
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
L = 0.0001
b = 0.0079
h = 0.405
t = np.arange(0, 1, 0.01)
y = 1/(b+(h*L)) * ((h*L) + b*np.exp((-h+(b/L)*t)))
plt.plot(t,y)
plt.grid()
plt.show()
  • 额外提示:处理numpy数组时,优先使用numpy自带的数学函数(如np.exp、np.sin等),这类函数天生支持数组运算,避免和标准库math模块的单值函数冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 15:34:49