简体   繁体   中英

Simpson's rule of Integration in Python

I have written a code for it, but whatever i try, its not working Can someone please take a look

def y(x):
    y=(x**3+2*x)/(x**2+2*x)

a=int(input("Enter lower limit:"))
b=int(input("Enter higher limit:"))
n=int(input("Enter no. of points:"))
h=1.0*(b-a)/n
x=[a+i*h for i in range(n)]
y=[y(i) for i in x]
I=1.0*(h/3)*(y[0]+y[-1]+4*sum(y[1:-1:2])+2*sum(y[2:-1:2]))
print (I)

It shows the error:

I=1.0*(h/3)*(y[0]+y[-1]+4*sum(y[1:-1:2])+2*sum(y[2:-1:2]))
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'

What does that mean?

You have to use return in your function:

def y(x):
    return (x**3+2*x)/(x**2+2*x)

a=int(input("Enter lower limit:"))
b=int(input("Enter higher limit:"))
n=int(input("Enter no. of points:"))
h=1.0*(b-a)/n
x=[a+i*h for i in range(n)]
y=[y(i) for i in x]
I=1.0*(h/3)*(y[0]+y[-1]+4*sum(y[1:-1:2])+2*sum(y[2:-1:2]))
print(I)

The error tells you that a value in the expression is None . This is a special value in Python that represents that there is no value. Since the expression is so large, you can find the problem by printing out parts of the expression, such as print(h) or print(y) to find the problem. Specifically, look at these lines from your code with an added print(y) :

def y(x):
    y=(x**3+2*x)/(x**2+2*x)


y=[y(i) for i in x]
print(y)

This will print out something like

[None, None, None, None]

This is because the y() function is missing a return statement. To fix the problem, just add return :

def y(x):
    return (x**3+2*x)/(x**2+2*x)

Tip: You name a function y and later assign y to a list. This reuse of a single name for two different things can cause problems later if you try to change this code. I suggest renaming the function to f :

def f(x):
    return (x**3+2*x)/(x**2+2*x)

y=[f(i) for i in x]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM