【问题标题】:Does this code fulfil its intended purpose?此代码是否实现了预期目的?
【发布时间】: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


【解决方案1】:

发件人: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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 2013-10-20
    • 1970-01-01
    • 2020-02-25
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多