python集成问题,函数用指数表示

2024-05-02 08:40:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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)

Tags: the函数inforinputbyreturn规则
1条回答
网友
1楼 · 发布于 2024-05-02 08:40:42

定义两个同名的集成例程。如果您调用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

和13;
和13;

尝试一下,如果仍然有错误,请发布错误消息。在

相关问题 更多 >