此代码是否符合其预期目的?

时间:2015-01-13 09:24:23

标签: python

这是我的梯形规则代码。我知道我的代码效率不高,但是我想知道你能看到代码中的任何错误吗?

不是运行时错误,而是代码中的实际错误。正如此代码实际上会产生梯形规则的正确结果吗?

在测试代码后,它产生了预期的结果,但是我被告知我的代码不正确,这是我查询的内容,因为我不知道如何。

感谢您的期待

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

1 个答案:

答案 0 :(得分:0)

来自:Trapezoidal rule in Python 检查此线程上的答案以获得更好的实现。

这是一个似乎返回正确值的修正。

from math import *

def trapeziumrule(f, a, b, n):
  c = float(b - a)
  h = float(c) / n # Change made here
  z = f(a) + f(b)
  for each in range(1, n):
      z = z + 2 * f(each * h + a)# creating a loop for my chosen n
  return z * (h / 2)

print( trapeziumrule(lambda x:x**2, 5, 10, 100))