Reputation: 19
When I write the following code, I get the following error. What am I doing wrong??
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()
Finally I get the following error:
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'
Upvotes: 1
Views: 277
Reputation: 15035
The error message is self-explanatory – the power operator **
is not defined for the built-in list
type.
They are however defined for np.array
s:
>>> np.array(range(5))**2
array([ 0, 1, 4, 9, 16])
Fix:
T = np.array([np.random.rand()*dt + p for p in P[:-1]])
Upvotes: 1