TypeError:不支持**或pow()的操作数类型:“list”和“int”。plt.p公司

2024-04-23 19:06:08 发布

您现在位置:Python中文网/ 问答频道 /正文

当我编写以下代码时,我得到以下错误。 我做错什么了??你知道吗

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'

Tags: inforreturnplot错误npdtplt
1条回答
网友
1楼 · 发布于 2024-04-23 19:06:08

错误消息是不言自明的–没有为内置的list类型定义幂运算符**。你知道吗

它们被定义为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]])

相关问题 更多 >