【发布时间】:2015-01-13 18:22:33
【问题描述】:
这是我的梯形规则代码。我知道我的代码效率不高,但是我想知道您能看到代码中的任何错误吗?
不是运行时错误,而是代码中的实际错误。就像这段代码实际上会为梯形规则产生正确的结果一样吗?
在测试代码后,它产生了预期的结果,但是我被告知我的代码不正确,这是我查询的内容,因为我不知道怎么做。
感谢期待
from math import *
def trapeziumrule(f, a, b, n):
c = float(b - a)# Was getting an error where all my h values would equal 0 so had to make this
h = float(c / n)# Then needed to make sure this would give a float too
z = f(a) + f(b)# my first and last term which do not need to be multiplied by 2
for each in range(1, n):
z = z + 2 * f(each * h + a)# creating a loop for my chosen n
return z * (h / 2)# should produce my answer
【问题讨论】:
-
我认为
c = float(b) - a会更好。否则,任何舍入错误都会在浮点转换之前发生。类似c/n -
def需要在from math ..的级别缩进
标签: python