【问题标题】:Riemann Sum Coding黎曼和编码
【发布时间】:2021-05-23 03:49:15
【问题描述】:

我只是用中点黎曼和在 Python 中测试我的手,但我似乎错过了一步,因为我的答案是错误的。这是我的代码示例:

from math import pi, sin
a=0
b=pi/2
n=10

dx=(b-a)/n
ends = [a+i*dx for i in range(n+1)]
mids=[(i+i-1)/2 for i in ends]
f = lambda x: x*sin(x)
area = [f(i)*dx for i in mids]
sum(area)

我的答案应该是 1,但我得到了 0.5022。我怀疑我在 mids 下的理解列表是错误的,但不知道如何解决它。任何帮助将不胜感激。

【问题讨论】:

  • 仅供参考,这位先生的名字是Riemann
  • 哈哈哈...感谢您指出这一点!

标签: python numerical-integration


【解决方案1】:

mids 应该是

mids = [(ends[i] + ends[i-1]) / 2 for i in range(1, len(ends))]

i-1 不是endsi-1th 元素。它只是 ith 元素减 1。

【讨论】:

    【解决方案2】:

    对于初学者来说,因为range(n+1),您将选择 11 个片段,而不是 10 个片段

    那么你的计算是错误的。

    ends[0] == 0 (a == 0, i == 0  => a+i*dx == 0)
    => mids[0] == -1/2 (i == ends[0] => (i+i-1)/2 == -1/2)
    

    如果你改用range(1, n+1),你会得到:

    ends[0] == pi/20 (a == 0, i == 1 => a+i*dx == pi/20)
    => mids[0] == pi/20-1/2 (i == ends[0] == pi/20 => (i+i-1)/2 == (pi/10-1)/2)
    

    这些仍然不正确 - ends 看起来不错,但 mids[0] 需要评估为 pi/40

    我的建议是使用调试器检查此处每个点的值,并确认它们是您认为应该的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多