[英]python integration issue, the function with exponential
I would like to integrate the function e^(-x**2/2) by simpson rule but it is keep having an error and I don't know what is the problem. 我想通过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)
You define 2 integration routines with the same name. 您定义了两个具有相同名称的集成例程。 Which one do you expect to run if you call simpson_rule()
? 如果您调用simpson_rule()
则希望运行哪一个? The first one is the special case where n=1. 第一个是n = 1的特殊情况。 You might rename it accordingly. 您可以相应地重命名。
Second, your call is print simpson_rule(f(x),a,b,n)
but you only need to hand over f()
to the function, like this print simpson_rule(f,a,b,n)
. 其次,您的调用是print simpson_rule(f(x),a,b,n)
但您只需要将f()
移交给函数,就像这个print simpson_rule(f,a,b,n)
。 You can see that f
is a function, and f()
is a function return value: 您可以看到f
是一个函数,而f()
是一个函数返回值:
def f(x): return x + 13 f <function f at 0x0000000002253D68> f(5) 18
Try it out and if you still have errors please post the error message(s). 试试看,如果仍然有错误,请发布错误消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.