python - 使用梯形规则定义积分(初学者)

标签 python

我的程序旨在使用 n 个梯形定义给定函数在两个数字 (x1,x2) 之间的积分。看起来,我部门的自动评估程序给出的答案与我的不同。问题是我不能在我的代码中发现任何错误...

def funct(x):
    val= -(1./6)*(x-1)*(x-2)*(x+2)*(x-4)
    return val


x1,x2,n=input()
Dx=float(x2-x1)/n
Sum=0
i=x1+Dx
while i<x2:
    val=funct(i)
    Sum+=val
    i+=Dx
Sum=2*Sum
val1=funct(x1)
val2=funct(x2)
S=(Dx/2)*(val1+val2+Sum)
print "%.3f" %S  

最佳答案

由于舍入问题,您的 while 循环始终包含 x 的最后一个值,请尝试使用精确整数运算

x0, x1 = -88.787529, 83.494648
n = 1942

dx = (x1-x0)/n
s = 0
i = 1
while i < n:

   # if we allow i == n, in the following row we'll have
   #   x0 + n*dx = x0 + n * (x1-x0) / n = x0 + x1 - x0 = x1
   # but we want to exclude the last term

   s = s + funct(x0+i*dx)
   i = i + 1
result = (s + funct(x0)/2.0 + funct(x1)/2.0)*dx

关于python - 使用梯形规则定义积分(初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27337073/

相关文章:

python - matplotlib 剪裁边缘处的曲面图颜色 python

python - 更新 DRF 中帖子的点赞

python - 如何杀死 celery 工作进程以重新启动进程

python - 如何打印字典中选定的项目?

python - boto3 改变 AWS ec2 实例状态

python - Python-如何正确终止threading.Timer类?

Python3如何尝试多个函数查找并赋值?

python - 有没有使用元素树从 xml 文件创建多个数据框的方法?

c++ - 在 python 中导入 C++ 类?

python - 使用 python 下载 HLS ( HTTP ) 流视频