开发者社区> 问答> 正文

用推导式近似黎曼和

我跟随sicp用黎曼和计算积分:

#+begin_src ipython :session sicp :results output
def integral(f, a, b, dx):
    add_dx = lambda x: x + dx
    return sum_recur(f, a+(dx/2), add_dx, b) * dx

from functools import lru_cache
@lru_cache(maxsize=None)
def sum_recur(term, a, next, b):
    if a > b: return 0
    return term(a) + sum_recur(term, next(a), next, b)

def cube(x): return x ** 3

print(integral(cube, 0, 1, 0.01))

#+end_src

#+RESULTS:
: 0.24998750000000042

它工作正常,但当实现它与列表理解

#+begin_src ipython :session sicp :results output
def integral(f, a, b, dx):
    return sum(a+dx/2+n*dx for n in range(b-1)) * dx
print(integral(cube, 0, 1, 0.001))
#+end_src

#+RESULTS:
: 5e-07

它没有像预期的那样工作,有什么问题吗? 问题来源StackOverflow 地址:/questions/59383439/approximate-the-riemann-sum-with-comprehensions

展开
收起
kun坤 2019-12-27 10:24:27 445 0
1 条回答
写回答
取消 提交回答
  • 在您的示例中,range(a-b)部分是取值范围(-1)。而且,您不会在任何地方调用多维数据集函数。 试试这个:

    def cube(x): return x ** 3
    
    def integral(f, a, b, dx):
        return sum(f(a+dx/2+n*dx) for n in range(int((b-a)/dx)) ) * dx
    
    print(integral(cube, 0, 1, 0.01))
    

    打印:

    0.24998750000000006
    
    2019-12-27 10:24:34
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载