简体   繁体   English

Python 中的辛普森积分规则

[英]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:您必须在 function 中使用return

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 .该错误告诉您表达式中的值为None This is a special value in Python that represents that there is no value.这是Python中的一个特殊值,表示没有值。 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.由于表达式如此之大,可以通过打印出表达式的部分内容来查找问题,例如print(h)print(y)来查找问题。 Specifically, look at these lines from your code with an added print(y) :具体来说,从您的代码中查看这些行并添加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.这是因为y() function 缺少return语句。 To fix the problem, just add return :要解决此问题,只需添加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.提示:您将 function 命名为y ,然后将y分配给列表。 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 :我建议将 function 重命名为f

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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