In the following code I have implemented simpsons rule. It is working correctly for my first function but for my second function I am getting an error.
So,
Is it possible to do this code without using np.linspace? and if not how do I fix it so my second function works?
def simps(f,a,b,N):
dx = (b-a)/N
x = np.linspace(a,b,N+1)
y = f(x)
S = dx/3 * np.sum(y[0:-1:2] + 4*y[1::2] + y[2::2])
return S
print(simps(lambda x:x**2, 5, 10, 100))
print(simps(lambda x: sin(x),0,pi/2,100))
which gives the output:
291.6666666666667
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-143-40325ae966e9> in <module>()
1 print(simps(lambda x:x**2, 5, 10, 100))
----> 2 print(simps(lambda x: sin(x),0,pi/2,100))
<ipython-input-142-860ce9822b06> in simps(f, a, b, N)
3 dx = (b-a)/N
4 x = np.linspace(a,b,N+1)
----> 5 y = f(x)
6 S = dx/3 * np.sum(y[0:-1:2] + 4*y[1::2] + y[2::2])
7 return S
<ipython-input-143-40325ae966e9> in <lambda>(x)
1 print(simps(lambda x:x**2, 5, 10, 100))
---->2 print(simps(lambda x: sin(x),0,pi/2,100))
TypeError: only size-1 arrays can be converted to Python scalars
linspaceis a very useful function to generate uniformly separated points. Remember to use function fromnumpyto efficiently map operations on arraysWith result