我想通过simpson规则集成函数e ^( - x ** 2/2) 但它一直有错误,我不知道是什么问题。
a=eval(input('a:'))
b=eval(input('b:'))
n=eval(input('n:'))
def f(x):
e**(-x**2/2)
h=(b-a)/n
s= f(a)+f(b)
def simpson_rule(f(x),a,b,n):
#Approximation by Simpson's rule
c=(a+b)/2.0
h=abs(b-a)/2.0
return h*(f(a)+4.0*f(c)+f(b))/3.0
def simpson_rule(f(x),a,b,n):
"""Approximates the definite integral of f from a to b by the composite Simpson's rule, using n subintervals"""
for i in range (1,n,2):
s+=4*f(a+i*h)
for i in range(2,n-1,2):
s+=2*f(a+i*h)
return s*h/3
print simpson_rule(f(x),a,b,n)
答案 0 :(得分:0)
您定义了两个具有相同名称的集成例程。如果拨打simpson_rule()
,您希望运行哪一个?
第一个是特殊情况,其中n = 1。您可以相应地重命名它。
其次,您的来电是print simpson_rule(f(x),a,b,n)
,但您只需要将f()
移交给该函数,例如print simpson_rule(f,a,b,n)
。
您可以看到f
是一个函数,f()
是一个函数返回值:
def f(x):
return x + 13
f
<function f at 0x0000000002253D68>
f(5)
18
尝试一下,如果仍有错误,请发布错误信息。