So I am trying to plot f = cos(x) using the trapezoidal rule but I keep getting an error saying:
TypeError: only length-1 arrays can be converted to Python scalars
I am not sure how the function is spitting out an array and not values.
import numpy as np
import matplotlib.pyplot as plt
import math as math
f = lambda x : math.cosh(4*x)
a = 0
b = 5
N = 8
# x and y values for the trapezoid rule
x = np.linspace(a,b,N 1)
y = f(x)
# X and Y values for plotting y=f(x)
X = np.linspace(a,b,100)
Y = f(X)
plt.plot(X,Y)
for i in range(N):
xs = [x[i],x[i],x[i 1],x[i 1]]
ys = [0,f(x[i]),f(x[i 1]),0]
plt.fill(xs,ys,'b',edgecolor='b',alpha=0.2)
plt.title('Trapezoid Rule, N = {}'.format(N))
plt.show()
CodePudding user response:
No need to mix frameworks, use:
f = lambda x : np.cosh(4*x)
CodePudding user response:
import numpy as np
import matplotlib.pyplot as plt
import math as math
f = lambda x : math.cosh(4*x)
a = 0
b = 5
N = 8
# x and y values for the trapezoid rule
x = np.linspace(a,b,N 1)
y = [f(i) for i in x] # this is a change
# X and Y values for plotting y=f(x)
X = np.linspace(a,b,100)
Y = [f(j) for j in X] #this is a change
plt.plot(X,Y)
for i in range(N):
xs = [x[i],x[i],x[i 1],x[i 1]]
ys = [0,f(x[i]),f(x[i 1]),0]
plt.fill(xs,ys,'b',edgecolor='b',alpha=0.2)
plt.title('Trapezoid Rule, N = {}'.format(N))
plt.show()
I have commented the changes.