gpt4 book ai didi

python - 类型错误 : unsupported operand type(s) for ** or pow(): 'list' and 'int' . plt.plot

转载 作者:行者123 更新时间:2023-12-01 08:06:57 24 4
gpt4 key购买 nike

当我编写以下代码时,出现以下错误。我做错了什么??

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 类型定义幂运算符 **

它们但是为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 - 类型错误 : unsupported operand type(s) for ** or pow(): 'list' and 'int' . plt.plot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55491403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com