Regular simpsons rule in numerical methods

112 Views Asked by At

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
1

There are 1 best solutions below

2
On BEST ANSWER

linspace is a very useful function to generate uniformly separated points. Remember to use function from numpy to efficiently map operations on arrays

import numpy as np
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: np.sin(x),0,np.pi/2,100))

With result

291.6666666666667
1.000000000338236