python - 类型错误:** 或 pow() 不支持的操作数类型:'list' 和 'int'。plt.plot
问题描述
当我编写以下代码时,出现以下错误。我究竟做错了什么??
def f(t):
return np.sin(t**2)
n = 20 # number of points for Riemann integration
a = 0; b = 2
P = np.linspace(a, b, n) # Standard partition constant width
dt = (b-a)/n
T = [np.random.rand()*dt + p for p in P[:-1]] # Randomly chosen point
再做几件事,然后:
plt.figure(figsize=(10,10))
plt.plot(T, f(T), '.', markersize=10)
plt.bar(P[:-1], f(T), width=dt, alpha=0.2, align='edge')
x = np.linspace(a, b, n*100) # we take finer spacing to get a "smooth" graph
y = f(x)
plt.plot(x, y)
plt.title('Riemann sum with n = {} points'.format(n))
plt.axis('off')
plt.show()
最后我得到以下错误:
Traceback (most recent call last):
File "riman.py", line 35, in <module>
plt.plot(T, f(T), '.', markersize=10)
File "riman.py", line 11, in f
return np.sin(t**2)
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
解决方案
错误消息是不言自明的——**
没有为内置list
类型定义幂运算符。
然而,它们是为 s 定义np.array
的:
>>> np.array(range(5))**2
array([ 0, 1, 4, 9, 16])
使固定:
T = np.array([np.random.rand()*dt + p for p in P[:-1]])
推荐阅读
- python - 如何将类型的 `__init__` 或 `__new__` 绑定到其他类实例?
- mysql - Windows 机器上的 MySQL Server 8.0,阻止名称解析
- java - 优先队列
> 不接受来自我的地图的条目对象 - javascript - 尝试从 JSON 追加获取数据
- c# - C#中的石头、纸、剪刀
- java - 未解决的要求:导入包:com.google.common.base
- python-3.x - GetObject 操作:尝试使用 boto 读取 S3 存储桶中的文件时拒绝访问
- python - 没有线程的 Python 计时器
- amazon-web-services - 为什么我不应该将我的所有 DynamoDB 项目都放在同一个分区键值中?
- docker - 文件更改时,两个带有 Nodemon 的后端服务器不会在 docker 容器中重新加载